795. 区间子数组个数

管理员

795. 区间子数组个数

class Solution {
    public int numSubarrayBoundedMax(int[] nums, int left, int right) {
        return (int) (cal(nums, right) - cal(nums, left - 1));
    }

    private long cal(int[] nums, int k) {
        int n = nums.length;
        long res = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] > k) continue;
            int j = i + 1;
            while (j < nums.length && nums[j] <= k) j++;
            int m = j - i;
            res += (long)m * (m + 1) / 2;
            i = j;
        }
        return res;
    }
}
class Solution {
    public int numSubarrayBoundedMax(int[] A, int L, int R) {
        return count(A,R)-count(A,L-1);
    }
    public int count(int[] A, int target){
        int cnt = 0; int res = 0;
        for(int x : A){
            if(x<=target){
                cnt++;
            }else{
                cnt = 0;
            }
            res += cnt;
        }
        return res;
    }
}
class Solution {
    public int numSubarrayBoundedMax(int[] A, int L, int R) {
        int len = A.length;
        Deque<Integer> sta = new ArrayDeque<>();
        int[] l = new int[len];
        int[] r = new int[len];
        for (int i = 0; i < len; i++) {
            while (!sta.isEmpty() && A[sta.peekLast()] < A[i]){
                int pre = sta.pollLast();
                r[pre] = i - 1;
            }
            l[i] = sta.isEmpty() ? 0 : sta.peekLast()+1;
            sta.addLast(i);
        }
        while (sta.size()>0){
            r[sta.pollLast()] = len - 1;
        }
        int ans = 0;
        for (int i = 0; i < len; i++) {
            if(A[i] >= L && A[i] <= R){
                ans += (r[i] - i + 1) * (i - l[i] + 1) ;
            }
        }
        return ans;
    }

    
}