Java easy to understand
\nclass Solution {\n    public int numSubarrayBoundedMax(int[] A, int L, int R) {\n        int prevHigh = -1, sum = 0, prev = 0;\n        for(int i = 0; i < A.l
```\nclass Solution {\n    public int numSubarrayBoundedMax(int[] A, int L, int R) {\n        int prevHigh = -1, sum = 0, prev = 0;\n        for(int i = 0; i < A.length; i++) {\n            if(A[i] >= L && A[i] <= R) {\n                prev = i - prevHigh;\n            }\n            else if(A[i] > R){\n                prev = 0;\n                prevHigh = i;\n            }\n            sum += prev;\n        }\n        return sum;\n    }\n}\n```\nExplanation: for each i, we count the number of subarrays ending with i (denoted as f(i)), and the result is the sum of f(i) over i. prevHigh is the previous position with respect to i where A[prevHigh] > R, and prev is the number of subarrays ending with i-1. So if A[i] > R, we reset prevHigh = i and prev = 0; if A[i] < L, then f(i) = f(i-1), because the subarray ending with i is basically extension of the previous subarray; if A[i] in [L, R], f(i) = i - prevHigh.
[]