Java Deque solution with some Useful points documented to make the Algorithm look brillaint


  • 0
    V
    public class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            if (nums == null || nums.length == 0 || k <= 0) return new int[0];
            
            int res[] = new int[nums.length - k + 1];
            int r = 0;
            
            Deque<Integer> d = new ArrayDeque<>();
            /**
                Two Invariants drive this  loop.
                (a) Elements in Deque are always sorted.
                (b) Elemnts in Deque lie in the k-width window.
                
                If you can grasp both on why they are true, the code is very trivial to understand.
            **/
            for (int i = 0; i < nums.length; i++) {
                while(!d.isEmpty() && nums[i] > nums[d.peekLast()]) d.pollLast();
                d.offerLast(i);
                
                // You dont need a while loop here, coz atmax one element can be out of the window at any given point of time.
                if (d.peek() < i - k + 1) d.poll();
                
                if (i >= k - 1) res[r++] = nums[d.peek()];
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.