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 :
A = [2, 1, 4, 3]
L = 2
R = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].

Naive Solution

In a brute-force way, we can check every subarray and count the total qualified ones.

public int numSubarrayBoundedMax(int[] A, int L, int R) {
    int result = 0;
    for(int i=0; i<A.length; i++){
        //If the current number is in the boundary, 
        //the current element itself is a valid subarray
        if(A[i]>=L && A[i]<=R){
        //If the current element is > R
        //no need to check subarray starting from this element
        for(int j=i+1; j<A.length; j++){
            //get max element in the subarray
            int max = A[i];
            for(int k=i; k<=j; k++){
               max = Math.max(max, A[k]); 
            //check if max is in boundary
    return result;

Time complexity is O(n^3).

Optimized Solution

LeetCode website provides an O(n) solution.

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