1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

main 2 mono queue, one is max, one is min

T: O(n)

S: O(n)

class Solution {
    class MonoQueue {
        Deque<Integer> max = new ArrayDeque<>();
        Deque<Integer> min = new ArrayDeque<>();
        
        public void offer(int num) {
            while (!max.isEmpty() && num > max.getLast()) {
                max.pollLast();
            }
            max.offerLast(num);
            
            while (!min.isEmpty() && num < min.getLast()) {
                min.pollLast();
            }
            min.offerLast(num);
        }
        public void poll(int num) {
            if (max.getFirst() == num) {
                max.pollFirst();
            }
            if (min.getFirst() == num) {
                min.pollFirst();
            }
        }
        public int max() {
            return max.getFirst();
        }
        public int min() {
            return min.getFirst();
        }
    }
    
    public int longestSubarray(int[] nums, int limit) {
        MonoQueue window = new MonoQueue();
        int windowSize = 0;
        int result = 0;
        int left = 0;
        
        for (int right = 0; right < nums.length; right++) {
            window.offer(nums[right]);
            windowSize++;
            while (window.max() - window.min() > limit) {
                window.poll(nums[left]);
                left++;
                windowSize--;
            }
            
            result = Math.max(result, windowSize);
        }
        return result;
    }
}

new version: Sliding win + monoQueue

latest one:

Last updated

Was this helpful?