题目
给你一个整数数组 nums 和两个整数:left 及 right 。找出 nums 中连续、非空且其中最大元素在范围 [left, right] 内的子数组,并返回满足条件的子数组的个数。
生成的测试用例保证结果符合 32-bit 整数范围。
示例
输入:nums = [2,1,4,3], left = 2, right = 3
输出:3
解释:满足条件的三个子数组:[2], [2, 1], [3]
输入:nums = [2,9,2,5,6], left = 2, right = 8
输出:7
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:单调栈+贡献值
⭐题解:https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum/solution/by-ac_oier-gmpt/
Java实现
class Solution {
public int numSubarrayBoundedMax(int[] nums, int left, int right) {
int n = nums.length;
int res = 0;
int[] l = new int[n + 10], r = new int[n + 10];
Arrays.fill(l, -1);
Arrays.fill(r, n);
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) r[stack.pop()] = i;
stack.push(i);
}
stack.clear();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && nums[stack.peek()] <= nums[i]) l[stack.pop()] = i;
stack.push(i);
}
for (int i = 0; i < n; i++) {
if (nums[i] < left || nums[i] > right) continue;
res += (i - l[i]) * (r[i] - i);
}
return res;
}
}