Sum of Subarray Ranges
Sum of Subarray Ranges is LeetCode 2104 (Medium). Given an integer array nums, the range of a subarray is its largest element minus its smallest element. Return the sum of the ranges of all non-empty contiguous subarrays.
numsholds up to 1,000 values, so an O(n²) scan is accepted; the follow-up asks for O(n).- Values run from −10⁹ to 10⁹, so the total needs a 64-bit integer.
- 1 <= nums.length <= 1000
- -10⁹ <= nums[i] <= 10⁹
Intuition
Each range is a max minus a min, so the whole total splits into two sums:
total = (sum of every subarray's max) − (sum of every subarray's min)
Then turn the counting around. Instead of visiting each subarray and asking for its max, visit each element and ask how many subarrays it is the max of. nums[i] stays the max while a subarray avoids every bigger value. If such a subarray can start at L places and end at R places, nums[i] is the max of L × R subarrays and adds nums[i] × L × R.
The min half needs no new code: the min of a subarray is minus the max of the same subarray with every sign flipped.
A sum over all subarrays of a max or a min is a contribution count: each element adds its value times the number of subarrays it wins. A range is two of those sums at once.
Approach
Before reading on, pick one element and count the subarrays where it is the largest value. What stops such a subarray from stretching further left, and further right? Aim for O(n).
Two ways to solve it
Each value adds itself times the number of subarrays it is the max of, minus the same for min.
- Linear: every index is pushed and popped once per scan.
- Follow-up: this is the O(n) answer the problem asks for.
The interview answer.
Fix a start, extend the end one step at a time, and keep the running min and max.
- Simple: no stacks, no tie rules.
- Enough here: 1,000 values means about 500,000 subarrays.
A good first answer before the follow-up.
Both are accepted at n ≤ 1,000; the stack count wins because it is linear and is what the follow-up asks for. The steps, code and live demo follow the stack count, and the running min and max code comes after the demo.
Write one function for the max half
sum_of_maxes(a) returns the sum of the maximums of all subarrays of a. The answer is sum_of_maxes(nums) + sum_of_maxes(−nums), because the second call returns minus the sum of the minimums.
Measure how far left each value reaches
Scan left to right, keeping a stack of indices whose values decrease. Pop every value smaller than a[i]; whatever stays on top is the nearest value at least as big. left[i] is the distance to it, or i + 1 when the stack is empty.
Measure how far right it reaches
Scan right to left the same way, but pop equal values too. right[i] is the distance to the nearest strictly bigger value, or n − i when there is none. Stopping at equals on only one side gives a tied max to its leftmost copy, so no subarray is counted twice.
Add each value times its count
a[i] is the max of exactly left[i] × right[i] subarrays: any start in its left stretch with any end in its right stretch. Add a[i] × left[i] × right[i] for every i.
Code in Python, C++ and Java
Running min and max
For each start i, extend the end j one step at a time. The new value can only lower the running min or raise the running max, so the range of nums[i..j] is ready in O(1) and is added straight to the total.
Common pitfalls
Popping equal values on both sides
while st and a[st[-1]] <= a[i]: # in both scans
while st and a[st[-1]] < a[i]: # left-to-right scan while st and a[st[-1]] <= a[i]: # right-to-left scan
With nums = [1, 3, 3], both 3s then claim the subarray [3, 3] and [1, 3, 3] as their max, and the result is 7 instead of 4. One scan must stop at an equal value so each tie has a single owner.
Adding into a 32-bit integer
int sum = 0;
long long sum = 0; // long in Java
For [1000000000, -1000000000, 1000000000] the answer is 6,000,000,000, about three times the largest 32-bit value. A single product a[i] × left[i] × right[i] can reach 2.5 × 10¹⁴.
Edge cases
[5, 5, 5]Every range is 0, so the answer is 0. The max half and the min half come out equal and cancel, which only happens if ties are owned by exactly one copy.
Complexity
left, right and stack arrays hold n entries each.Sum of Subarray Ranges FAQ
How is this different from Sum of Subarray Minimums?
Sum of Subarray Minimums (LeetCode 907) counts only the min half and reports it modulo 10⁹ + 7. Here both halves are needed, values can be negative, and the exact answer is returned, which always fits in 64 bits because n is at most 1,000.
Can the count be done in a single stack scan?
Yes. When an index is popped, both of its limits are known: the new top of the stack on the left and the index doing the popping on the right. Add its share at that moment and append a sentinel at the end to flush the stack. It is still O(n), just harder to read.