Sum of Subarray Minimums
Add up the smallest value of every subarray by counting how many subarrays each value is the smallest in.
Given an array of integers arr
Example 1
Output: 17
Explanation: the subarrays are [3], [1], [2], [4], [3, 1], [1, 2], [2, 4], [3, 1, 2], [1, 2, 4], [3, 1, 2, 4], with minimums 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Their sum is 17.
Example 2
Output: 444
The Idea
Picture four cards in a row: 3, 1, 2 and 4. Pick any subarray, such as the cards 1 and 2 together, or all four cards, and write down the smallest card in it. Four cards give ten subarrays, and their smallest cards add up to 17, as Example 1 lists.
Listing every subarray works for four cards, but a longer row has many more: n cards give n(n + 1)/2 subarrays, about 50 million for 10,000 cards. Do we really need to look at each one? Read the minimums in Example 1 again: 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. The value 1 shows up six times. So the question can be turned around: for each card, in how many subarrays is it the smallest?
Number the positions from 0, and take the 1 at index 1. A subarray keeps 1 as its smallest card as long as it does not take in a smaller card, and this row has none. The subarray can start at index 0 or 1, two choices, and end at index 1, 2 or 3, three choices. Any start goes with any end, so 1 is the smallest in 2 × 3 = 6 subarrays and adds 1 × 6 = 6 to the total.
Look at the picture below. Each row shows one value in orange, and the blue cells next to it are the stretch where it stays the smallest. In the row labelled "2 as minimum", the stretch stops at the 1 on its left, so 2 has 1 start and 2 ends, and adds 2 × 2 = 4. The column labelled "adds to the total" sums to 17, the answer.
So each value needs only two facts: how far left and how far right it can reach before it meets a smaller value. In other words, it needs the nearest smaller value on each side. Equal values need some care, though. In [2, 2][2, 2]
Solution Approach
Turning the per-value count into code means settling three things: how to find the nearest smaller value on each side, how to count equal values once, and how to keep the total small. First, though, a look at the simple way.
Adding up every subarray directly
Why not just add up every subarray? Fix a start, then move the end right one step at a time, keeping the smallest value seen so far. Each subarray then costs one step, but there are still n(n + 1)/2 of them, so the time grows with n². Counting per value never visits the subarrays at all.
Finding the nearest smaller value with a stack
How do we find the nearest smaller value on the left of every value, without searching back each time? Walk the array from left to right and keep a stack of positions. A stack is a pile where you add to the top and take from the top. Before adding position iarr[i]
Nothing is lost by taking them off. For every value further right, arr[i]arr[i]
In Example 1, when the walk reaches the 1 at index 1, it takes off the 3, and the stack is empty, so 1 can start anywhere from index 0. The values left in the stack never go down from bottom to top, so this pile is called a monotonic stack. A second walk, from right to left, finds the nearest smaller value on the right in the same way.
Counting equal values once
What happens with equal values? If each 2 in [2, 2][2, 2]
The first 2 then reaches both cells, the second 2 reaches only itself, and the subarray [2, 2]
Keeping the total small
How big can the total get? One value can be the smallest in a huge number of subarrays, and a large value, say one billion, times that count is far beyond what an intlong
Java Solution
The method sumSubarrayMins
- First, create two arrays of length
.n will hold the number of start positions whereleft[i] stays the smallest, andarr[i] the number of end positions. Also createright[i] , anstack of positions.ArrayDeque - Walk
from left to right. Pop every position on top ofi whose value is larger thanstack . If the stack is then empty, nothing on the left stopsarr[i] , so it hasarr[i] start positions. Otherwisei + 1 isleft[i] . Then pushi - stack.peek() .i - Clear the stack and walk
from right to left. This time pop positions whose value is larger than or equal toi . An empty stack givesarr[i] end positions, otherwisen - i isright[i] . Then pushstack.peek() - i .i - Finally, a third loop adds
for eacharr[i] × left[i] × right[i] to ai namedlong , taking the remainder modulototal , the constant 1,000,000,007, each time, and returnsMOD as antotal .int
The main[2, 2][1, 1, 1]
import java.util.ArrayDeque;
import java.util.Deque;
public class SumOfSubarrayMinimums {
private static final int MOD = 1000000007;
public static int sumSubarrayMins(int[] arr) {
int n = arr.length;
int[] left = new int[n]; // start positions where arr[i] stays the minimum
int[] right = new int[n]; // end positions where arr[i] stays the minimum
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && arr[stack.peek()] > arr[i]) {
stack.pop();
}
left[i] = stack.isEmpty() ? i + 1 : i - stack.peek(); // stops at smaller or equal
stack.push(i);
}
stack.clear();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
stack.pop();
}
right[i] = stack.isEmpty() ? n - i : stack.peek() - i; // stops at strictly smaller
stack.push(i);
}
long total = 0;
for (int i = 0; i < n; i++) {
total = (total + (long) arr[i] * left[i] * right[i]) % MOD;
}
return (int) total;
}
public static void main(String[] args) {
System.out.println(sumSubarrayMins(new int[] {3, 1, 2, 4}));
System.out.println(sumSubarrayMins(new int[] {11, 81, 94, 43, 3}));
System.out.println(sumSubarrayMins(new int[] {2, 2}));
System.out.println(sumSubarrayMins(new int[] {1, 1, 1}));
System.out.println(sumSubarrayMins(new int[] {5}));
int big = 1000000000;
System.out.println(sumSubarrayMins(new int[] {big, big, big}));
}
}
Running it prints:
17
444
6
6
5
999999965
The values 17 and 444 match the two examples. The two lines that read 6 come from [2, 2][1, 1, 1]
Those two lines depend on the two walks comparing differently. Run with larger-or-equal pops in both walks, the same method prints 8 and 10, because equal values claim subarrays they share. With only larger pops in both walks, it prints 4 and 3, because no value claims them.
The last line comes from three values of 1,000,000,000. They form six subarrays, so the true sum is 6,000,000,000, and its remainder modulo 1,000,000,007 is 999,999,965.
Complexity
The work is two walks with the stack, plus one loop that adds up each value's share.
- Time: O(n), because each walk pushes every position once and pops it at most once, so the inner
loops pop at most n times per walk in total. The last loop computes one product per value.while - Space: O(n), because
andleft hold n counts each, and the stack can hold all n positions, for example when the left-to-right walk goes over a rising array and never pops.right
The same question, how far a value can stretch before it meets a smaller one, finds the widest rectangle for each bar in