Sliding Window Maximum

Hard Sliding Window AI round

nums is a list of whole numbers and k is a window size: a window is k numbers of nums next to each other.

The window slides along nums one place at a time, from the window that starts at position 0 to the one that ends at the last position.

Return the largest number in each window, in the order the windows come.

Example 1

Input: nums = [4,-2,7,1,0,5,3], k = 3
Output: [7,7,7,5,5]

The windows are [4, -2, 7], [-2, 7, 1], [7, 1, 0], [1, 0, 5] and [0, 5, 3]. 7 is the largest of the first three, and 5 of the last two.

Example 2

Input: nums = [9,8,6,2], k = 2
Output: [9,8,6]

Example 3

Input: nums = [-3,-3,-1,-6], k = 4
Output: [-1]

Constraints

  • 1 ≤ nums.length ≤ 7 × 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
  • 1 ≤ k ≤ nums.length

Watch the explanation

More Sliding Window

All Sliding Window problems