Monotonic Queue

Keep a deque of candidate indexes in sorted order so the maximum or minimum of a sliding window, or of a range of earlier DP states, is always at the front. The whole scan is O(n).

Overview

The idea

A sliding window of size k moves one step at a time. Its sum is easy to keep: add the element that enters, subtract the one that leaves. Its maximum is not. When the largest element leaves, the next largest can be anywhere in the window, and finding it by scanning costs O(k) per step.

A monotonic queue keeps only the elements that could still become a window maximum, in decreasing order, in a deque (a queue that can add and remove at both ends). The front is always the current maximum. Every index enters the deque once and leaves once, so the whole scan is O(n).

The saving is large. Take n = 100,000 and k = 1,000. Scanning each window for its maximum costs about 99 million comparisons, since (n − k + 1) · k = 99,001,000. That is O(n·k). The monotonic deque needs at most about 200,000 deque operations, since 2n = 200,000. That is O(n).

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio