Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A.
Since the answer may be large, return the answer modulo 10^9 + 7.
Example 1:
Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.
Note:
1 <= A.length <= 30000
1 <= A[i] <= 30000
Solution:
class Solution {
public int sumSubarrayMins(int[] A) {
long sum = 0;
int mod = (int) 1e9 + 7;
Deque<Integer> stack = new ArrayDeque();
for (int i = 0; i <= A.length; i ++) {
int curr = i == A.length ? 0 : A[i];
while (!stack.isEmpty() && curr < A[stack.peekFirst()]) {
int index = stack.pop();
// the distance between element A[index] and its previous smaller element
int left = index - (stack.isEmpty() ? -1 : stack.peekFirst());
// the distance between element A[index] and its next smaller element
int right = i - index;
sum = (sum + A[index] * left * right) % mod;
}
stack.push(i);
}
return (int) (sum % mod);
}
}