#239

Sliding Window Maximum

candidate master · 1460 · lc hard +32 · verified · 48.5% accepted · 20,304 likes · top 34%

play →

Description

You have an integer array nums and a sliding window of width k that moves one position to the right at each step, starting at the leftmost position. At each position the window exposes k consecutive elements.

Return the array of maximum values observed in the window at each position.

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7

Example 2:

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

Code

1
2
3