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
| class Solution {
public int numSubarrayBoundedMax(int[] nums, int left, int right) { int n = nums.length; int[] l = new int[n], r = new int[n]; Arrays.fill(l, -1); Arrays.fill(r, n); Deque<Integer> stack = new ArrayDeque<>(); for (int i = 0; i < n; ++i) { int num = nums[i]; while (!stack.isEmpty() && nums[stack.peek()] <= num) stack.pop(); if (!stack.isEmpty()) l[i] = stack.peek(); stack.push(i); } stack.clear(); for (int i = n - 1; i >= 0; --i) { int num = nums[i]; while (!stack.isEmpty() && nums[stack.peek()] < num) stack.pop(); if (!stack.isEmpty()) r[i] = stack.peek(); stack.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; }
}
|