-
Notifications
You must be signed in to change notification settings - Fork 14
/
Solution795.java
42 lines (35 loc) · 1.18 KB
/
Solution795.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
39
40
41
42
package leetcode.stack.monotonic;
import java.util.Arrays;
import java.util.Stack;
public class Solution795 {
public static void main(String[] args) {
System.out.println(new Solution795().numSubarrayBoundedMax(new int[]{0, 1, 3, 2, 3, 0, 1, 4}, 2, 3));
}
public int numSubarrayBoundedMax(int[] nums, int left, int right) {
Stack<Integer> stack = new Stack<>();
int[] l = new int[nums.length];
Arrays.fill(l, -1);
int[] r = new int[nums.length];
Arrays.fill(r, nums.length);
for (int i = 0; i < nums.length; i++) {
while (!stack.isEmpty() && nums[i] >= nums[stack.peek()]) {
r[stack.pop()] = i;
}
stack.push(i);
}
stack.clear();
for (int i = nums.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) {
l[stack.pop()] = i;
}
stack.push(i);
}
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (left <= nums[i] && nums[i] <= right) {
res += (r[i] - i) * (i - l[i]);
}
}
return res;
}
}