Sliding Window Maximum

HardSliding Window

A window of size k slides across the array nums from left to right, one position at a time, always covering exactly k consecutive elements. Return an array with the maximum value of every window position, in order. The result has nums.length - k + 1 entries.

A solution that rescans each window works but takes O(n * k) time. Aim for O(n).

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

Examples

Example 1

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

The windows are [1,3,-1], [3,-1,-3], [-1,-3,5], [-3,5,3], [5,3,6], [3,6,7], with maxima 3, 3, 5, 5, 6, 7.

Example 2

Input: nums = [1], k = 1
Output: [1]

One window, holding one value.

Example 3

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

The window covers the whole array.

JavaScript you'll use: Stacks, queues and deques Arrays: create, read, update

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
function maxSlidingWindow(nums, k) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.