-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathsum_of_subarray_minimum100.cpp
More file actions
40 lines (31 loc) · 1.05 KB
/
Copy pathsum_of_subarray_minimum100.cpp
File metadata and controls
40 lines (31 loc) · 1.05 KB
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
class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
int n = arr.size();
const int MOD = 1e9 + 7;
vector<int> pse(n), nse(n);
stack<int> st;
// Previous Smaller (strictly smaller)
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);
}
while(!st.empty()) st.pop();
// Next Smaller (smaller or equal)
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);
}
long long ans = 0;
for(int i = 0; i < n; i++) {
long long left = i - pse[i];
long long right = nse[i] - i;
ans = (ans + arr[i] * left % MOD * right % MOD) % MOD;
}
return ans;
}
};