Sum of Subarray Ranges

You are given an integer array `nums`. The range of a subarray is the difference between its largest and smallest element. Return the sum of the ranges of all subarrays of `nums`. A subarray is a contiguous non-empty sequence of elements. The answer can exceed 32 bits.

30:00

Sum of Subarray Ranges
medium
Free written solution
Topics
Companies

You are given an integer array nums. The range of a subarray is the difference between its largest and smallest element. Return the sum of the ranges of all subarrays of nums. A subarray is a contiguous non-empty sequence of elements. The answer can exceed 32 bits.

Example 1:
Input: {"nums":[1,2,3]}
Output: 4
Constraints:
  • 1≤nums.length≤10001 \leq nums.\text{length} \leq 1000

  • −109≤nums[i]≤109-10^9 \leq nums[i] \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3]}
pass 1: Σ max (decreasing stack)
pass 2: Σ min (increasing stack)

1

0

2

1

3

2

Sum of (max - min) over all subarrays = (sum of every subarray max) - (sum of every subarray min). Count how many subarrays each element is the max of, then the min of.

× max···
× min···
Σmax 0
Σmin 0
Σmax − Σmin = 0
Variables
VariableValue
sumMax0
sumMin0
total0
DepthFunction Call
Stack empty
0/17