Skip to content

Commit e0bf033

Browse files
committed
Time: 92 ms (57.09%), Space: 40.4 MB (80.97%) - LeetHub
1 parent d48d935 commit e0bf033

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
const int mod = 1e9 + 7;
3+
public:
4+
int sumSubarrayMins(vector<int>& arr) {
5+
int n = arr.size();
6+
int area[n][2];
7+
8+
// ple
9+
stack<int> s;
10+
for(int i = 0; i < n; i++){
11+
12+
while(!s.empty() and arr[s.top()] > arr[i]) s.pop();
13+
if(s.empty())
14+
area[i][0] = 0;
15+
else
16+
area[i][0] = s.top() + 1;
17+
s.push(i);
18+
}
19+
20+
// nle
21+
stack<int> st;
22+
for(int i = n - 1; i >= 0; i--){
23+
24+
while(!st.empty() and arr[st.top()] >= arr[i]) st.pop();
25+
if(st.empty())
26+
area[i][1] = n - 1;
27+
else
28+
area[i][1] = st.top() - 1;
29+
st.push(i);
30+
}
31+
32+
int sum = 0;
33+
for(int i = 0; i < n; i++){
34+
int lo = area[i][0], hi = area[i][1];
35+
// cout << i << " " << lo << " " << hi << endl;
36+
long prod = ((i - lo + 1) % mod * (hi - i + 1) % mod) % mod;
37+
prod = (prod % mod * arr[i] % mod) % mod;
38+
sum = (sum + prod) % mod;
39+
// sum = (sum + ((arr[i] % mod * ((i - lo + 1) * (hi - i + 1)) % mod)) % mod) % mod;
40+
}
41+
42+
cout << mod << endl;
43+
return sum ;
44+
}
45+
};

0 commit comments

Comments
 (0)