题目截图
题目分析
- 无脑单调栈左右找更大
- 注意一边不取等,一边取等,避免重复
- 找到包含当前元素为最大值的区间个数,左 * 右即可
python
class Solution:def numSubarrayBoundedMax(self, nums: List[int], left_: int, right_: int) -> int:n &#61; len(nums)left, st &#61; [-1] * n, []for i, v in enumerate(nums):while st and nums[st[-1]] < v: st.pop()if st: left[i] &#61; st[-1]st.append(i)right, st &#61; [n] * n, []for i in range(n - 1, -1, -1):while st and nums[st[-1]] <&#61; nums[i]: st.pop()if st: right[i] &#61; st[-1]st.append(i)ans &#61; 0for i in range(n):l, r &#61; i - left[i], right[i] - iif left_ <&#61; nums[i] <&#61; right_:ans &#43;&#61; l * rreturn ans
java
class Solution {public int numSubarrayBoundedMax(int[] nums, int left, int right) {int n &#61; nums.length;int[] L &#61; new int[n], R &#61; new int[n];Arrays.fill(L, -1);Arrays.fill(R, n);Deque<Integer> st &#61; new ArrayDeque<>();for (int i &#61; 0; i < n; &#43;&#43;i) {while (!st.isEmpty() && nums[st.peek()] < nums[i]) st.pop();if (!st.isEmpty()) L[i] &#61; st.peek();st.push(i);}st.clear();for (int i &#61; n - 1; i >&#61; 0; --i) {while (!st.isEmpty() && nums[st.peek()] <&#61; nums[i]) st.pop();if (!st.isEmpty()) R[i] &#61; st.peek();st.push(i);}int ans &#61; 0;for (int i &#61; 0; i < n; &#43;&#43;i) {if (left <&#61; nums[i] && nums[i] <&#61; right) {ans &#43;&#61; (i - L[i]) * (R[i] - i);}}return ans;}
}
- int[] l &#61; new int[n];
- Deque st &#61; new ArrayDeque<>();
- st.peak()
- st.pop()
- st.push(i)
总结