Github
795. Number of Subarrays with Bounded Maximum
[Medium] We are given an array A
of positive integers, and two positive integers L
and R
(L <= R
).
Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least L
and at most R
.
Example :
Input:
A = [2, 1, 4, 3]
L = 2
R = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
Note:
- L, R and
A[i]
will be an integer in the range[0, 10^9]
. - The length of
A
will be in the range of[1, 50000]
.
题目:给定一个元素都是正整数的数组A
,正整数 L
以及 R
(L <= R
)。求连续、非空且其中最大元素满足大于等于L
小于等于R
的子数组个数。
思路:双指针,参考link。cnt
表示以A[i]
结尾的且满足条件的子数组数组。因此分为三种情况:A[i]
落在[L,R]
区间内,那么满足条件的子数组个数为i-j+1
;如果A[i] < L
,那么其子数组个数由上一个状态的cnt
决定;如果A[i] > R
,那么没有以A[i]
结尾的子数组能满足条件。
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
int n = A.size();
int res = 0;
for(int i = 0, j = 0, cnt = 0; i < n; ++i){
if(L <= A[i] && A[i] <= R){
cnt = i - j + 1;
}
else if(A[i] > R){
cnt = 0;
j = i + 1;
}
res += cnt;
}
return res;
}
};