forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.java
38 lines (38 loc) · 1.07 KB
/
Solution2.java
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
class Solution {
public int numSubarrayBoundedMax(int[] nums, int left, int right) {
int n = nums.length;
int[] l = new int[n];
int[] r = new int[n];
Arrays.fill(l, -1);
Arrays.fill(r, n);
Deque<Integer> stk = new ArrayDeque<>();
for (int i = 0; i < n; ++i) {
int v = nums[i];
while (!stk.isEmpty() && nums[stk.peek()] <= v) {
stk.pop();
}
if (!stk.isEmpty()) {
l[i] = stk.peek();
}
stk.push(i);
}
stk.clear();
for (int i = n - 1; i >= 0; --i) {
int v = nums[i];
while (!stk.isEmpty() && nums[stk.peek()] < v) {
stk.pop();
}
if (!stk.isEmpty()) {
r[i] = stk.peek();
}
stk.push(i);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
if (left <= nums[i] && nums[i] <= right) {
ans += (i - l[i]) * (r[i] - i);
}
}
return ans;
}
}