Skip to content

Practice Sum of Subarray Ranges

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#2104
LeetCode Problem

Sum of Subarray Ranges

Problem Statement

You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Example 2: Example 3: Constraints: Follow-up: Could you find a solution with O(n) time complexity?

Source: Sum of Subarray Ranges on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
nums = [1,2,3]
Output
4

# Example 2

Input
nums = [1,3,3]
Output
4

# Example 3

Input
nums = [4,-2,-3,4,1]
Output
59

Constraints

1 <= nums.length <= 1000
-10^9 <= nums[i] <= 10^9

Related LeetCode Problems

Practice more problems similar to Sum of Subarray Ranges.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.