Java O(n) concise solution with explanations
The idea is to consider the subarrays ending at each index i in the input array A. With i fixed, the subarray will be uniquely determined by its start index j, 
The idea is to consider the subarrays ending at each index `i` in the input array `A`. With `i` fixed, the subarray will be uniquely determined by its start index `j`, and the subarray itself will be denoted as `A[j, i]` (left inclusive, right inclusive). If there are no additional constraints, `j` can take any integer value in the range `[0, i]`. But now we do want the maximum element of the subarray to lie in the range `[L, R]`, which has two implications:

1. There is **at least one** element in the subarray that is `>= L`.
2. There is **no** element in the subarray that is `> R`.

To meet the first condition, we need to scan `j` from `i` down to `0` until we find the first element that is `>= L`; we denote the index of this element as `r` (if no such element exists, `r = -1`). To guarantee the second condition, we need to continue the scanning until we find the first element that is `> R`; we denote the index of this element as `l` (again `l = -1` if no such element exists). Note that we always have `l <= r` as long as `L <= R`. Then we conclude `j` can only take integer value in the range `(l, r]` (left exclusive, right inclusive). Since each `j` value corresponds to a unique subarray, this further implies the total number of subarrays ending at index `i` with their maximum element lying in the range `[L, R]` is given by `r - l`.

Now the key is to find the indices `l` and `r` for each `i`. Of course we cannot afford to do the actual scanning of `j` as described above. The observation here is that `l` is essentially the largest index such that `l <= i && A[l] > R`, while `r` is the largest index such that `r <= i && A[r] >= L`. Therefore, as we are scanning the input array from left to right, `l` will be updated only if `A[i] > R` and `r` will be updated only if `A[r] >= L`. So here is the `O(n)` time, `O(1)` space Java solution:

<br>

```
public int numSubarrayBoundedMax(int[] A, int L, int R) {
    int res = 0;
        
    for (int i = 0, l = -1, r = -1; i < A.length; i++) {
        if (A[i] > R) l = i;
        if (A[i] >= L) r = i;
        res += r - l;
    }
        
    return res;
}
```
[]