Sum of Subarray Ranges - Problem
You are given an integer array nums. The range of a subarray is defined as the difference between the largest and smallest element in that subarray.
Your task is to return the sum of all subarray ranges of nums.
A subarray is a contiguous non-empty sequence of elements within an array. For example, if nums = [1, 2, 3], the subarrays are: [1], [2], [3], [1, 2], [2, 3], and [1, 2, 3].
Example: For nums = [1, 2, 3]:
- Subarray [1]: range = 1 - 1 = 0
- Subarray [2]: range = 2 - 2 = 0
- Subarray [3]: range = 3 - 3 = 0
- Subarray [1, 2]: range = 2 - 1 = 1
- Subarray [2, 3]: range = 3 - 2 = 1
- Subarray [1, 2, 3]: range = 3 - 1 = 2
Total sum: 0 + 0 + 0 + 1 + 1 + 2 = 4
Input & Output
example_1.py ā Simple Array
$
Input:
[1, 2, 3]
āŗ
Output:
4
š” Note:
Subarrays: [1] (range=0), [2] (range=0), [3] (range=0), [1,2] (range=1), [2,3] (range=1), [1,2,3] (range=2). Total: 0+0+0+1+1+2=4
example_2.py ā Single Element
$
Input:
[1]
āŗ
Output:
0
š” Note:
Only one subarray [1] with range = 1-1 = 0
example_3.py ā Larger Array
$
Input:
[1, 3, 3]
āŗ
Output:
4
š” Note:
Subarrays: [1] (range=0), [3] (range=0), [3] (range=0), [1,3] (range=2), [3,3] (range=0), [1,3,3] (range=2). Total: 0+0+0+2+0+2=4
Constraints
- 1 ⤠nums.length ⤠1000
- -109 ⤠nums[i] ⤠109
- Note: The array can contain duplicate elements
Visualization
Tap to expand
Understanding the Visualization
1
Identify the insight
Range = Max - Min, so sum of ranges = sum of all maximums - sum of all minimums
2
Use monotonic stacks
Track when each element is maximum/minimum using decreasing/increasing stacks
3
Count contributions
For each element, count how many subarrays it dominates as max/min
4
Calculate final result
Multiply each element by its contribution count and sum the differences
Key Takeaway
šÆ Key Insight: Instead of generating O(n²) subarrays, we use monotonic stacks to mathematically count each element's contribution as maximum/minimum, reducing time complexity from O(n³) to O(n).
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code