239. Sliding Window Maximum

Hard

Problem:

Given an array nums, find the maximum sliding window of size k by moving the sliding window to the right end.

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

https://leetcode.com/problems/sliding-window-maximumarrow-up-right

Solution:

Brute Force

Because the maximum value of the window is calculated every time, in this case, the time complexity is O(n)O(n).

Deque

Time Limit Exceeded

It's difficult to improve the part where the sliding window has to move one step at a time. Therefore, there is no choice but to minimize the calculation of the maximum value. By saving the previous maximum value and only checking if the new value is larger as it moves one step at a time, and recalculating the entire window only when the maximum value falls out of the window, it can be improved into a form (FIFO - First In First Out).

Better Implementation

Reference: https://www.youtube.com/watch?v=DfljaUwZsOkarrow-up-right

Last updated