Calculate the Sum of Subarray Minimums using a Monotonic Stack
To find the sum of the minimums of all possible subarrays, the problem is transformed into calculating how many subarrays each element arr[i] acts as the minimum value.
For each element, you must determine the distance to the nearest smaller element to its left and the nearest smaller element to its right. The number of subarrays where arr[i] is the minimum is calculated as: (distance to left smaller) * (distance to right smaller).
Key logic:
- Use a monotonic stack to find the boundaries (left and right) where the current element is the minimum.
- To handle duplicate values and avoid double-counting subarrays, use a strict inequality (
<) on one side and a non-strict inequality (<=) on the other. - The final result is the sum of
arr[i] * left_distance * right_distancefor alli, modulo $10^9 + 7$.
class Solution {
static int mod = (int) 1e9 + 7;
public int sumSubarrayMins(int[] arr) {
int n = arr.length;
int[] left = new int[n], right = new int[n];
int[] stack = new int[n];
int p = -1;
for (int i = 0; i < n; i++) {
// Maintain monotonic increasing stack
while (p != -1 && arr[i] < arr[stack[p]]) {
int pop = stack[p--];
right[pop] = i - pop;
}
// Distance to the previous smaller element
left[i] = p == -1 ? (i + 1) : (i - stack[p]);
stack[++p] = i;
}
// Process remaining elements in stack
while (p != -1) {
int pop = stack[p--];
right[pop] = n - pop;
}
long ans = 0;
for (int i = 0; i < n; i++)
ans = (ans + (1L * left[i] * right[i] * arr[i] % mod)) % mod;
return (int) ans;
}
}