LeetCode #2104 Medium

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.

  • nums holds 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.
Constraints
  • 1 <= nums.length <= 1000
  • -10⁹ <= nums[i] <= 10⁹
monotonic-stackarraycontribution
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def subArrayRanges(self, nums):
▶3 return self.sum_of_maxes(nums) + self.sum_of_maxes([-x for x in nums])
▶4 
▶5 def sum_of_maxes(self, a):
▶6 n = len(a)
▶7 left, right, st = [0] * n, [0] * n, []
▶8 for i in range(n):
▶9 while st and a[st[-1]] < a[i]:
▶10 st.pop()
▶11 left[i] = i - st[-1] if st else i + 1
▶12 st.append(i)
▶13 st = []
▶14 for i in range(n - 1, -1, -1):
▶15 while st and a[st[-1]] <= a[i]:
▶16 st.pop()
▶17 right[i] = st[-1] - i if st else n - i
▶18 st.append(i)
▶19 return sum(a[i] * left[i] * right[i] for i in range(n))
nums1to 02to 13to 2from 0from 1from 2maxstartsendsadds××=max summin sumanswer00−=measure how far each value reaches
starts as max[1, 2, 3]left reach
ends as max[1, 1, 1]right reach
The grid holds one box per subarray: the row is where it starts and the column is where it ends, so there are 6 boxes. The stack scans give every value its reach: how many starts and how many ends keep it the largest value. Each value will fill a rectangle of boxes.
nums1to 02to 13to 2from 01from 1from 2maxstartsendsadds1111××=max summin sumanswer10−=1 is the max of 1 subarray → adds 1
value1index 0
subarrays1 × 1starts × ends
max sum1
Moving left from index 0, there is nothing, so the only start is index 0. Moving right, index 1 holds a bigger 2, so an end stops at index 0. 1 starts × 1 ends = 1 subarray, all with max 1.
nums1to 02to 13to 2from 012from 12from 2maxstartsendsadds2214××=max summin sumanswer50−=2 is the max of 2 subarrays → adds 4
value2index 1
subarrays2 × 1starts × ends
max sum5
Moving left from index 1, nothing is bigger, so a start can sit anywhere from index 0 to 1. Moving right, index 2 holds a bigger 3, so an end stops at index 1. 2 starts × 1 ends = 2 subarrays, all with max 2.
nums1to 02to 13to 2from 0123from 123from 23maxstartsendsadds3319××=max summin sumanswer140−=3 is the max of 3 subarrays → adds 9
value3index 2
subarrays3 × 1starts × ends
max sum14
Moving left from index 2, nothing is bigger, so a start can sit anywhere from index 0 to 2. Moving right, there is nothing, so the only end is index 2. 3 starts × 1 ends = 3 subarrays, all with max 3.
nums1to 02to 13to 2from 0012from 123from 23minstartsendsadds1133××=max summin sumanswer143−=1 is the min of 3 subarrays → adds 3
value1index 0
subarrays1 × 3starts × ends
min sum3
Now the same count for the smallest value, done in the code by running the max count on the negated array. 1 stays the min for 1 starts × 3 ends = 3 subarrays. Subtracting it from those boxes turns each one from its max into its range.
nums1to 02to 13to 2from 0012from 101from 23minstartsendsadds2124××=max summin sumanswer147−=2 is the min of 2 subarrays → adds 4
value2index 1
subarrays1 × 2starts × ends
min sum7
Now the same count for the smallest value, done in the code by running the max count on the negated array. 2 stays the min for 1 starts × 2 ends = 2 subarrays. Subtracting it from those boxes turns each one from its max into its range.
nums1to 02to 13to 2from 0012from 101from 20minstartsendsadds3113××=max summin sumanswer1410−=3 is the min of 1 subarray → adds 3
value3index 2
subarrays1 × 1starts × ends
min sum10
Now the same count for the smallest value, done in the code by running the max count on the negated array. 3 stays the min for 1 starts × 1 ends = 1 subarray. Subtracting it from those boxes turns each one from its max into its range.
nums1to 02to 13to 2from 0012from 101from 20maxstartsendsadds××=max summin sumanswer14104−=ranges add up to 4
max sum14
min sum10
answer4
Every box now shows its subarray's range, and every box was filled exactly once in each half. So the answer is the max sum minus the min sum: 14 − 10 = 4, the same as adding up the grid, without ever visiting a box one by one.
05

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.

▶1class Solution:
▶2 def subArrayRanges(self, nums):
▶3 total = 0
▶4 for i in range(len(nums)):
▶5 lo = hi = nums[i]
▶6 for j in range(i, len(nums)):
▶7 lo = min(lo, nums[j])
▶8 hi = max(hi, nums[j])
▶9 total += hi - lo
▶10 return total
06

Common pitfalls

Popping equal values on both sides

✗ Wrong
while st and a[st[-1]] <= a[i]:  # in both scans
✓ Right
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

✗ Wrong
int sum = 0;
✓ Right
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¹⁴.

07

Edge cases

All values equal, such as [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.

08

Complexity

Time
O(n)
Space
O(n)
Two calls, each with two stack scans. In every scan an index is pushed once and popped at most once. The left, right and stack arrays hold n entries each.
09

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.