Solved Using Priority Queue


  • 0
    N
    public int[] maxSlidingWindow(int[] nums, int k) {
            if(nums == null || nums.length <= 1) {
                return nums;
            }
    
            PriorityQueue maxHeap = new PriorityQueue(Collections.reverseOrder());
    
            int[] maxElements = new int[nums.length -k +1];
    
            for(int i=0,l=0;l+k<=nums.length;l++) {
                for (int j = i; j < l+k; j++) {
                    maxHeap.add(nums[j]);
                }
                maxElements[l] = (int) maxHeap.peek();
                maxHeap.remove(nums[l]);
                i=l+k;
            }
            return maxElements;
        }
    

Log in to reply
 

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