-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path25 NOV Sum of Subarray Minimums
41 lines (33 loc) · 1.02 KB
/
25 NOV 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
class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
stack<int> s1, s2;
int n = arr.size();
vector<int> next_smaller(n), prev_smaller(n);
for(int i = 0;i<n;i++){
next_smaller[i] = n-i-1;
prev_smaller[i] = i;
}
for(int i = 0;i<n;i++){
while(!s1.empty() && arr[s1.top()]>arr[i]){
next_smaller[s1.top()] = i - s1.top() - 1;
s1.pop();
}
s1.push(i);
}
for(int i = n-1;i>=0;i--){
while(!s2.empty() && arr[s2.top()]>=arr[i]){
prev_smaller[s2.top()] = s2.top() - i - 1;
s2.pop();
}
s2.push(i);
}
long ans = 0;
int mod = 1e9 + 7;
for(int i = 0;i<n;i++){
ans = (ans + (long)arr[i] * (prev_smaller[i]+1) * (next_smaller[i]+1)) % mod;
ans %= mod;
}
return ans;
}
};