-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSum of Subarray Minimums
44 lines (41 loc) · 1.15 KB
/
Sum of Subarray Minimums
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
36
37
38
39
40
41
42
43
44
const int MOD = 1e9 + 7;
class Solution {
public:
vector<int> findNSE(vector<int>& arr) {
int n = arr.size();
vector<int> nse(n);
stack<int> st;
for (int i = n - 1; i >= 0; i--) {
while (!st.empty() && arr[st.top()] >= arr[i]) {
st.pop();
}
nse[i] = st.empty() ? n : st.top();
st.push(i);
}
return nse;
}
vector<int> findPSEE(vector<int>& arr) {
int n = arr.size();
vector<int> pse(n);
stack<int> st;
for (int i = 0; i < n; i++) {
while (!st.empty() && arr[st.top()] > arr[i]) {
st.pop();
}
pse[i] = st.empty() ? -1 : st.top();
st.push(i);
}
return pse;
}
int sumSubarrayMins(vector<int>& arr) {
vector<int> nse = findNSE(arr);
vector<int> psee = findPSEE(arr);
int total = 0;
for (int i = 0; i < arr.size(); i++) {
int left = i - psee[i];
int right = nse[i] - i;
total = (total + (right * left * 1LL * arr[i]) % MOD) % MOD;
}
return total;
}
};