You are given an integer array nums and a window of size k that slides from the very left of the array to the very right, one position at a time. Return the maximum of each window. Aim for O(n) time.
nums = [1,3,-1,-3,5,3,6,7], k = 3[3,3,5,5,6,7]nums = [1], k = 1[1]i: if the front index left the window (≤ i − k), pop it from the front ⌛≤ nums[i], pop it from the back 🗑️ (it can never be a max again)i to the backi ≥ k − 1), the answer is nums[front] 👑Every index is pushed once and popped at most once, so the deque does at most 2n operations in total, no matter how big k is. Checking every window directly costs (n − k + 1) · k comparisons, which is O(n·k). The watch-out: store indices, not values, so you can tell when the front has slid out of the window.
k = 1 → every element is its own max. k = n → one window, one answer. Decreasing array → nothing is ever popped from the back and the deque fills up to k. Duplicates → using ≤ drops the older copy, which is safe because the newer one lasts longer.