leetcode 907 - Sum of Subarray Minimums

https://leetcode.com/problems/sum-of-subarray-minimums/
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/170750/JavaC%2B%2BPython-Stack-Solution

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

Example 1:

Input: arr = [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.
Example 2:

Input: arr = [11,81,94,43,3]
Output: 444

Constraints:

1 <= arr.length <= 3 * 10^4
1 <= arr[i] <= 3 * 10^4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
int sumSubarrayMins(vector<int>& A) {
int size = A.size();
int mod = 1e9 + 7;

vector<int> prev(size), next(size);
stack<int> st;

for (int i = 0; i < size; i++) {
while (!st.empty() && A[st.top()] >= A[i])
st.pop();

prev[i] = st.empty() ? -1 : st.top();
st.push(i);
}

while (!st.empty())
st.pop();

for (int i = size - 1; i >= 0; i--) {
while (!st.empty() && A[st.top()] > A[i])
st.pop();
next[i] = st.empty() ? size : st.top();
st.push(i);
}

int sum = 0;
for (int i = 0; i < size; i++) {
sum = (sum + (i - prev[i]) * (next[i] - i) * A[i]) % mod;
}

return sum;
}
};