You are given an integer array nums
. A sliding window of size k
moves from the leftmost side of the array to the right, one element at a time. You can only see k
numbers in the window. The sliding window moves one step to the right each time.
Return the maximum sliding window.
The brute force approach won't work, it times out. We need to optimize the approach. In fact, for two adjacent sliding windows, they share k-1
elements, and only 1
element changes. We can optimize based on this characteristic. We can maintain a monotonic decreasing window. When moving to the right, we pop the values from the left side of the window that exceed the window size because only the window's maximum value is needed. We only need to ensure that the values within the window are decreasing, meaning that if a new value is added, all smaller existing values are popped. The leftmost value is the maximum in the window. First, we define a window to store the indices of the decreasing values, and an array to store the maximum values. Then, we iterate through the given array. If the current index is greater than or equal to the window size and the first value in the decreasing index window is outside the current window, we pop it. Then, we traverse backward, and if there is a value in the decreasing window and it is less than the value about to be added, we pop it. Finally, if the window can form k
elements, we start to take the maximum value, which is the first value of the decreasing window, and add it to the maximum value array. After the loop ends, we return the maximum value array.