To achieve O(n) complexity, we need to avoid re-scanning the window for every slide; we must maintain a data structure that tracks potential maximums in amortized constant time.
Use a Monotonic Deque (Double-Ended Queue) to store indices of elements in decreasing order of their values. This ensures the maximum element for the current window is always at the head of the deque.
As we iterate, discard indices from the back of the deque that point to values smaller than the current element, as they can no longer be the maximum.
Also, prune the head of the deque if the index is outside the sliding window's range (index < i - k + 1).