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;
}
};