Sliding window maximum
Keep a deque of indices whose values are decreasing. When a new value arrives, everything smaller behind it is discarded — those can never be a maximum again, because the newcomer is bigger and outlives them. The front is always the current window's maximum. O(n) total.
Overview
The observation that does the work
If a[j] comes before a[i] and a[j] ≤ a[i], then a[j] can never be the maximum of any future window — every window containing it from now on also contains the bigger, later a[i]. So it can be thrown away the moment a[i] arrives.
What survives is a decreasing sequence, and its front is the maximum of the current window by construction. No scan is ever needed.
Step through it
What to watch
- Smaller values behind a larger one are discarded immediately.
- The front is the answer without any scanning.
- Indices are stored, not values — that is how expiry is detected.
Say this out loud
"Monotonic deque of indices, values decreasing. A new value evicts everything smaller from the back, because they can never win again. The front is the answer, and I drop it once it falls out of the window. Every index is pushed and popped once, so O(n)."