You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
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
Input: nums = [1], k = 1
Output: [1]
The simplest way to solve the sliding window maximum problem is to compute the maximum of each window separately. For each position in the array, consider all the elements in the sliding window starting from that position, and find the maximum element. This method checks each sliding window one by one and finds the maximum element.
Using a deque, we maintain the indexes of the array. The key is to maintain the elements of the deque in a monotonically decreasing order of their values. This means the max value for the window is at the front of the deque. We ensure that elements outside the current window or smaller elements than the current are removed.
This approach uses a max heap to store the elements of the current window. The largest element in the window is always at the top of the heap. We remove elements from the heap that are out of the window's current range.