-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
46 lines (35 loc) · 1.08 KB
/
Copy pathsolution.cpp
File metadata and controls
46 lines (35 loc) · 1.08 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
class Solution {
public:
int sumSubMins(vector<int> &arr) {
int n = arr.size();
vector<int> left(n), right(n);
stack<int> st;
// Find distance to Previous Less Element
for(int i = 0; i < n; i++){
while(!st.empty() && arr[st.top()] > arr[i])
st.pop();
if(st.empty())
left[i] = i + 1;
else
left[i] = i - st.top();
st.push(i);
}
// Clear stack for next computation
while(!st.empty()) st.pop();
// Find distance to Next Less Element
for(int i = n - 1; i >= 0; i--){
while(!st.empty() && arr[st.top()] >= arr[i])
st.pop();
if(st.empty())
right[i] = n - i;
else
right[i] = st.top() - i;
st.push(i);
}
long long ans = 0;
for(int i = 0; i < n; i++){
ans += (long long)arr[i] * left[i] * right[i];
}
return ans;
}
};