1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { private static final int MOD = (int) (1e9 + 7);
public int sumSubarrayMins(int[] arr) { int n = arr.length; int[] left = new int[n], right = new int[n]; Arrays.fill(right, n); Deque<Integer> stack = new ArrayDeque<>(); stack.push(-1); for (int i = 0; i < n; ++i) { while (stack.size() > 1 && arr[stack.peek()] >= arr[i]) { right[stack.pop()] = i; } left[i] = stack.peek(); stack.push(i); } long ans = 0; for (int i = 0; i < n; ++i) { ans += (long) arr[i] * (i - left[i]) * (right[i] - i); } return (int) (ans % MOD); } }
|