Sliding Window Maximum

Given nums = [1,3,-1,-3,5,3,6,7], and k = 3, return the max sliding window as [3,3,5,5,6,7].

  • Time: O(klog(n))
  • Space: O(n)
public int[] maxSlidingWindow(int[] nums, int k) {
    if (nums == null || nums.length == 0) {
        return new int[]{};
    }
    PriorityQueue<Integer> pq = 
            new PriorityQueue<>(Collections.reverseOrder());
    int[] ret = new int[nums.length + 1 - k];
    for (int i = 0; i < nums.length; i++) {
        pq.offer(nums[i]);
        if (i >= k - 1) {
            if (pq.size() > k) {
                pq.remove(nums[i - k]);
            }
            ret[i - k + 1] = pq.peek();
        }
    }
    return ret;
}

results matching ""

    No results matching ""