LeetCode – Number of Subarrays with Bounded Maximum (Java)

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

Java Solution

The boundary for this problem is for each element, not sum. It is easy to misunderstand the problem, as there are many questions related about sum.

Given the array in the sample [2,1,4,3], we can convert it to an array [0,0,1,0], which means if the element is within the boundary, it's 0. We then count the number of subarrays.

Given an array, the total number of subarray follows the following pattern:

[0]       -> 1
[0,0]     -> 2 + 1 (single-element subarray + 2-element subarray)
[0,0,0]   -> 3 + 2 + 1
[0,0,0,0] -> 4 + 3 + 2 + 1

Therefore, the solution is countBelowBoundary of R - countBelowBoundary of (L-1).

public int numSubarrayBoundedMax(int[] A, int L, int R) {
    return countBelowBoundary(A, R)-countBelowBoundary(A,L-1);
}
 
public int countBelowBoundary(int[] A, int bound){
    int count = 0;
    int temp = 0;
 
    for(int a: A){
        if(a<=bound){
            temp = temp +1;
            count += temp;
        }else{
            temp = 0;
        }
    }
    return count;
}

Time is O(N) and space is O(1).

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>