Dynamic Programming21 sections · 916 units
Open in Course

The Deque Approach

Data structure

Store lines in a deque (double-ended queue), ordered by slope. The front has the smallest slope (optimal for small xx). The back has the largest slope (optimal for large xx). For queries: check if the second line beats the first at current xx.

If yes, pop the front. Repeat until the front is optimal. For insertions: add new lines at the back. But first, remove lines that become dominated. Both operations are amortized O(1)O(1) because each line enters and leaves at most once.