-
Notifications
You must be signed in to change notification settings - Fork 3
/
795.cpp
32 lines (31 loc) · 930 Bytes
/
795.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
32
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& nums, int left, int right) {
stack<int> st;
st.push(-1);
int n = nums.size();
int res = 0;
for (int i = 0; i < n; ++i) {
while (st.size() > 1 && nums[i] > nums[st.top()]) {
int top = st.top();
st.pop();
if (nums[top] >= left && nums[top] <= right) {
res += (i - top ) * (top - st.top());
}
}
if (nums[i] <= right) st.push(i);
else {
while (!st.empty()) st.pop();
st.push(i);
}
}
while (st.size() > 1) {
int top = st.top();
st.pop();
if (nums[top] >= left && nums[top] <= right) {
res += (n - top) * (top - st.top());
}
}
return res;
}
};