-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path907.cpp
31 lines (31 loc) · 907 Bytes
/
907.cpp
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
class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
long long ans = 0;
long long mod = 1e9 + 7;
stack<int> st;
int n = arr.size();
for (int i = 0; i < n; ++i) {
while (!st.empty() && arr[i] <= arr[st.top()]) {
int j = st.top();
st.pop();
long long left = -1;
long long right = i;
if (!st.empty()) left = st.top();
ans += (right - j) * (j - left) * arr[j];
ans %= mod;
}
st.push(i);
}
while (!st.empty()) {
int j = st.top();
st.pop();
long long left = -1;
long long right = n;
if (!st.empty()) left = st.top();
ans += (right - j) * (j - left) * arr[j];
ans %= mod;
}
return ans;
}
};