Given an array nums and a window size k that slides from left to right one step at a time, return the maximum of each window.
Keep a deque of indices whose values are strictly decreasing. A new value evicts smaller values from the back (they can never be a max again). The front is the window max; drop it once it slides out.
1function maxSlidingWindow(nums: number[], k: number): number[] {2const dq: number[] = [], res: number[] = [];3for (let i = 0; i < nums.length; i++) {4while (dq.length && nums[dq.at(-1)!] <= nums[i]) dq.pop();5dq.push(i);6if (dq[0] <= i - k) dq.shift();7if (i >= k - 1) res.push(nums[dq[0]]);8}9return res;10}
i = 0, nums[i] = 1.
Space: play/pause · ←/→: step