Start learning free

LESSON 457 OF 678 · SLIDING WINDOW

Sliding Window Maximum

Practice O(n)

You get an array of integers nums and a window size k.

The window covers k values in a row. It starts over the first k values. Then it moves one step to the right at a time. Its last stop covers the last k values.

Return an array with the largest value in the window at each stop, from left to right.

 

Example 1:

Input: nums = [5, 1, -2, 8, 3, 3, -6, 4], k = 3
Output: [5, 8, 8, 8, 3, 4]
Explanation: The window stops 6 times:
[5, 1, -2]   largest 5.
[1, -2, 8]   largest 8.
[-2, 8, 3]   largest 8.
[8, 3, 3]    largest 8.
[3, 3, -6]   largest 3.
[3, -6, 4]   largest 4.

Example 2:

Input: nums = [6, -1, 9, 2], k = 4
Output: [9]
Explanation: The window is as long as nums.
It stops only once.

Example 3:

Input: nums = [9, 7, 7, 2], k = 2
Output: [9, 7, 7]
Explanation: The window stops 3 times:
[9, 7]   largest 9.
[7, 7]   largest 7.
[7, 2]   largest 7.
After the first stop, the 9 is out of the window.

 

Constraints:

  • nums has 1 to 100,000 values.
  • Each value is from -10,000 to 10,000.
  • k is from 1 to the length of nums.

Note:

Your algorithm should run in O(n) time, where n is the length of nums, and use O(n) extra space. Finding each window's maximum from scratch takes O(n · k) time, too slow for the largest tests.

STEP 1 OF 10
    Ctrl + Enter to check