Algorithm-Day11-Sliding-Window-Maximum-lc-239
π§© Problem Description
You are given an array of integers nums, and there is a sliding window of size k that moves from the very left to the very right.
Return the maximum value in each window as it slides.
Example:
1 | Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 |
π‘ Brute Force (Too Slow)
For each window, scan the k elements to find the max.
1 | // O(n * k) |
- β Works
- β Too slow when
nums.lengthis large
π‘ Optimal Approach: Monotonic Queue (Deque)
π§ Key Idea
Use a deque (double-ended queue) to keep indices of elements in decreasing order:
- Front of deque always holds the index of the current maximum
- Before adding a new index, remove all indices whose values are less than the current number
- Remove indices that are out of the window
β Why a deque?
It helps us maintain a βcandidate listβ for the maximum of the current window β always in O(1) time per operation.
π’ Java Code
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n)
Each element is added and removed at most once from the deque - Space Complexity: O(k)
For the deque storing at mostkelements
βοΈ Summary
- The monotonic queue is a powerful technique for max/min in sliding windows
- Much more efficient than brute force (O(n) vs O(n Γ k))
- Common pattern in other problems like
lc-862,lc-1438, andlc-1425
When dealing with βsliding window max/minβ, always think of using a deque to maintain order.