Sum of Subarray Ranges
Pattern: Monotonic stack
The sum of (max - min) over all subarrays equals the sum of maximums minus the sum of minimums. Each sum is a contribution count with a monotonic stack: when a value is popped, it was the max (or min) of (m - left) × (i - m) subarrays.
The problem
Return the sum of max - min over every contiguous subarray of nums. [1, 2, 3] gives 4 and [1, 3, 3] gives 4.
The answer can exceed 32 bits, so it is a long.
Think first
- Can the range of each subarray be split into two separate sums?
- Which earlier problem sums minimums of all subarrays?
- What changes for maximums?
Hints
Brute force, and why it fails
For each start, extend right keeping a running max and min: O(n²).
The key insight
Linearity: split the sum, and solve each half with the contribution trick in O(n).
Dry run
10
21
32
| sumMax | 14 |
|---|
nums = [1, 2, 3]. The maximums of the six subarrays add up to 1 + 2 + 3 + 2 + 3 + 3 = 14.
Step 1 of 3
The plan
total(a, isMax):
for i from 0 to n (i == n flushes):
while stack and (i == n or top beats-or-ties a[i]):
m = pop; left = top or -1
sum += a[m] * (m - left) * (i - m)
push i
answer = total(nums, max) - total(nums, min)
Complexity
- Time
O(n)- Space
O(n)
Two passes, each pushing and popping every index once.
Edge cases
- All equal: 0.
- One value: 0.
- Large values: the products need 64 bits.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public long subArrayRanges(int[] nums) {
return total(nums, true) - total(nums, false); // sum of maximums minus sum of minimums
}
private long total(int[] a, boolean max) { // sum over subarrays of their max (or min)
int n = a.length;
long sum = 0;
Deque<Integer> st = new ArrayDeque<>();
for (int i = 0; i <= n; i++) {
while (!st.isEmpty() && (i == n || (max ? a[st.peek()] <= a[i] : a[st.peek()] >= a[i]))) {
int m = st.pop(); // a[m] was the max (min) from just after the new top to i - 1
int left = st.isEmpty() ? -1 : st.peek();
sum += (long) a[m] * (m - left) * (i - m);
}
st.push(i);
}
return sum;
}
}C++
class Solution {
public:
long long subArrayRanges(vector<int>& nums) {
return total(nums, true) - total(nums, false); // sum of maximums minus sum of minimums
}
long long total(vector<int>& a, bool mx) { // sum over subarrays of their max (or min)
int n = static_cast<int>(a.size());
long long sum = 0;
vector<int> st;
for (int i = 0; i <= n; i++) {
while (!st.empty() && (i == n || (mx ? a[st.back()] <= a[i] : a[st.back()] >= a[i]))) {
int m = st.back(); // a[m] was the max (min) from just after the new top to i - 1
st.pop_back();
int left = st.empty() ? -1 : st.back();
sum += static_cast<long long>(a[m]) * (m - left) * (i - m);
}
st.push_back(i);
}
return sum;
}
};Python
class Solution:
def subArrayRanges(self, nums: list[int]) -> int:
return self.total(nums, True) - self.total(nums, False) # sum of maximums minus sum of minimums
def total(self, a: list[int], is_max: bool) -> int: # sum over subarrays of their max (or min)
n, s, st = len(a), 0, []
for i in range(n + 1):
while st and (i == n or (a[st[-1]] <= a[i] if is_max else a[st[-1]] >= a[i])):
m = st.pop() # a[m] was the max (min) from just after the new top to i - 1
left = st[-1] if st else -1
s += a[m] * (m - left) * (i - m)
st.append(i)
return sCommon mistakes
- Mixing the tie rules so that a subarray is counted twice or not at all.
- Forgetting the flush at
i == n.