A window k elements wide sits over the start of the integer array nums. It slides one place to the right at a time until its right edge reaches the last element. Return the largest value inside the window at each position, from left to right.
There are nums.length - k + 1 positions, so that is the length of the answer.
The 12 stays the largest for the first three windows. Once it slides out, [11,-5,7] peaks at 11, and the last window [-5,7,1] at 7.
Equal values are fine: the window [5,5] has largest value 5.
When k equals the array's length, the window never moves and there is a single answer.
Constraints
1 <= nums.length <= 10⁵-10⁴ <= nums[i] <= 10⁴1 <= k <= nums.lengthOnce a bigger value enters the window, every smaller value to its left can never be a window's maximum again: it will slide out sooner, and until then the bigger value beats it.
Each window shares k - 1 of its values with the window before it. Reading all k values again for every window is n · k steps, which at n = 10⁵ and k = 5 · 10⁴ is billions. The way out is to carry something from one window to the next, so that each slide costs little.
Time O(n)Space O(k)
The full walkthrough and code are part of Premium