Problem Description
Given an array of integers (nums) and a window size (k), the task is to slide the window from the left of the array to the right by one position at a time and return an array of the maximum values in each window.
Key Insights
- Use a deque (double-ended queue) to maintain the indices of potential maximum elements in a decreasing order.
- Ensure that the deque always has the current window's indices by removing elements that fall outside the current window.
- Only add elements that are greater than the ones at the back of the deque, thus preserving a monotonic decreasing order.
- The maximum for the current window is at the front of the deque.
Space and Time Complexity
Time Complexity: O(n) where n is the number of elements in nums, since each element is processed at most twice. Space Complexity: O(k), as the deque stores indices for at most k elements at any time.
Solution
The solution uses a monotonic deque to maintain indices of potential maximum elements in the current window. As the window slides, we:
- Remove indices from the front if they are out of the window.
- Remove indices from the back if the current element is larger, because they cannot be the maximum if the current element is in the window.
- Append the current index.
- After the first k elements, the element at the front of the deque is the maximum for that window. This approach ensures that each element is pushed and popped from the deque only once, achieving an overall O(n) time complexity.