Dynamic Programming21 sections · 916 units
Open in Course

Monotonic Queue - How It Works

Add and remove

The deque stores indices in increasing order of their dpdp values (for finding minimum). When you process position ii:

1.1. Remove indices from the front if they're outside the window [ik,i1][i-k, i-1].

2.2. The front index gives you the minimum dpdp value in the window.

3.3. Remove indices from the back while their dpdp values are dp[i]\geq dp[i].

4.4. Add ii to the back. Each index enters once and leaves once. Total time: O(n)O(n)

Time complexity: O(n)O(n) amortized for all operations combined.

Space complexity: O(k)O(k) for the deque.