Problem statement
Given an array of numbers and a window size k, report the largest value inside every window of k consecutive values. The windows move one position at a time, so there are n - k + 1 answers.
A direct scan costs k work per window, which is too slow when k is large. The deque version reads each value once, because a value that is beaten by a later one can never be the maximum of any window that contains both.
Examples
Input[1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output[3, 3, 5, 5, 6, 7]
The first window is 1, 3, -1, so 3. The 5 at index 4 beats everything held before it.
Input[5, 4, 3], k = 3
Output[5]
Only one window fits, so there is one answer and the falling values never replace the front.
The walkthrough is part of Premium
The statement and the examples above stay free. The full how-to-solve walkthrough, the cost notes in plain words and the interactive step-by-step visualizer unlock with a Premium plan.
See pricing