Maximum of Every Sliding Window of Size K

Implement maxOfEverySlidingWindow

Given an array nums and an integer k, return an array where each value is the maximum of the window nums[i..i+k-1], for every valid window position as the window slides from the start of the array to the end. Recomputing the max of every window from scratch is correct but wasteful — most of a window's elements are shared with the window right before it. The fix is a deque that only ever holds candidates that could still become a future window's maximum, kept in strictly decreasing order of value. Because the front of a decreasing deque is always the biggest value currently in the window, reading the answer for each window becomes O(1), and every index is pushed and popped from the deque at most once — giving O(n) overall despite the nested-looking while loops inside the for.

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3

Output: [3,3,5,5,6,7]

Example 2:

Input: nums = [9,11], k = 2

Output: [11]

Example 3:

Input: nums = [4,-2], k = 2

Output: [4]

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • 1 ≤ k ≤ nums.length

nums =

[1, 3, -1, -3, 5, 3, 6, 7]

k =

3