-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path06.SumofSubarrayMinimums.cpp
More file actions
47 lines (43 loc) · 1.64 KB
/
06.SumofSubarrayMinimums.cpp
File metadata and controls
47 lines (43 loc) · 1.64 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
41
42
43
44
45
46
47
int sumSubarrayMins(vector<int>& arr) {
vector<int> nse = nextSmaller(arr);
vector<int> pse = prevSmaller(arr);
int n = arr.size();
long long tot = 0;
const int MOD = 1'000'000'007;
for (int i = 0; i < n; i++) {
long long left = i - pse[i];
long long right = nse[i] - i;
long long contrib = (left * right) % MOD;
contrib = (contrib * (arr[i] % MOD)) % MOD;
tot += contrib;
if (tot >= MOD)
tot -= MOD;
}
return (int)tot;
}
vector<int> nextSmaller(vector<int>& arr) {
stack<int> st;
int n = arr.size();
vector<int> ans(n);
for (int i = n - 1; i >= 0; i--) {
while (!st.empty() && arr[st.top()] > arr[i]) {
st.pop();
}
ans[i] = st.empty() ? n : st.top();
st.push(i);
}
return ans;
}
vector<int> prevSmaller(vector<int>& arr) {
stack<int> st;
int n = arr.size();
vector<int> ans(n);
for (int i = 0; i < n; i++) {
while (!st.empty() && arr[st.top()] >= arr[i]) {
st.pop();
}
ans[i] = st.empty() ? -1 : st.top();
st.push(i);
}
return ans;
}