题目地址:
https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/description/
给定一个长 n n n数组 A A A,和一个范围 [ l , r ] [l,r] [l,r],问最大值位于这个范围的子数组的个数。
思路是单调栈。开一个严格单调下降的栈,在pop的时候,就能得到pop出的元素的右边最近的比它大的值的下标,和左边最近的不小于它的下标,这样能求出以其为最大值的子数组的个数。求个总和即可。代码如下:
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& a, int l, int r) {
int res = 0, n = a.size();
stack<int> stk;
for (int i = 0; i < n; i++) {
while (stk.size() && a[stk.top()] < a[i]) {
int t = stk.top(); stk.pop();
int lc = t - (stk.empty() ? -1 : stk.top()), rc = i - t;
if (l <= a[t] && a[t] <= r) res += lc * rc;
}
stk.push(i);
}
while (stk.size()) {
int t = stk.top(); stk.pop();
int lc = t - (stk.empty() ? -1 : stk.top()), rc = n - t;
if (l <= a[t] && a[t] <= r) res += lc * rc;
}
return res;
}
};
时空复杂度 O ( n ) O(n) O(n)。