Number of Subarrays with Bounded Maximum

Description

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].

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

More efficient implementation:

class Solution {
public:
    int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
        int count = 0;
        int j = -1, k = -1;
        for(int i = 0; i < A.size(); ++i){
            if(A[i] > R)
                k = i;
            if(A[i] >= L)
                j = i;
            count += j - k;
        }
        return count;
    }
};

Last updated