The Naive Approach
Scanning all K elements for every shift takes O(N*K) time. For large windows, this is brutally slow.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given an array and a sliding window of size K, find the maximum element in the window at each step. This is the classic problem that proves the immense power of the Deque (Double Ended Queue).
Scanning all K elements for every shift takes O(N*K) time. For large windows, this is brutally slow.
We use a Deque to store indices. We maintain it such that the values it points to are strictly decreasing. This guarantees the absolute maximum for the current window is always at the `front`.
Elements leave the Deque for two reasons: (1) from the back, because a larger element came in and rendered them permanently useless. (2) from the front, because the window simply slid past their index.