Contribution with monotonic stacks
Time O(n) Space O(n)left[i] = distance to the previous smaller element; right[i] = distance to the next smaller-or-equal. Sum arr[i] × left × right.
arr = [3, 1, 2, 4]left reach(list)
Step 1/4Left pass: 3 reaches 1 cell (itself). 1 pops the bigger 3, reaching 2 cells. 2 and 4 stop at a smaller neighbour: 1 each.
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public int sumSubarrayMins(int[] arr) {
int n = arr.length;
int[] left = new int[n], right = new int[n];
Deque<Integer> st = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!st.isEmpty() && arr[st.peek()] > arr[i]) st.pop();
left[i] = st.isEmpty() ? i + 1 : i - st.peek();
st.push(i);
}
st.clear();
for (int i = n - 1; i >= 0; i--) {
while (!st.isEmpty() && arr[st.peek()] >= arr[i]) st.pop();
right[i] = st.isEmpty() ? n - i : st.peek() - i;
st.push(i);
}
long total = 0, MOD = 1_000_000_007L;
for (int i = 0; i < n; i++) total = (total + (long) arr[i] * left[i] * right[i]) % MOD;
return (int) total;
}
}Verdict: Turns O(n²) subarrays into n contributions.