Number of Subarrays with Bounded Maximum
Description
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].Solution
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
// dp[i]: number of satisfied subarrays in the first i elements
// in the first i elements
// let j be the index of the right most number that are in [L, R]
// let k be the index of the right most number that are > R
// if A[i] > R: dp[i + 1] = dp[i]
// if A[i] <= R:
// number of satisfied subarrays that does not contain A[i]: dp[i]
// number of satisfied subarrays that contains A[i]: j - k
// so dp[i + 1] = dp[i] + j - k
int count = 0;
int j = -1, k = -1;
for(int i = 0; i < A.size(); ++i){
if(A[i] > R){
k = i;
}else if(A[i] >= L){
j = i;
}
count += max(j - k, 0);
}
return count;
}
};Last updated