Dynamic Programming21 sections · 916 units
Open in Course

When Queries Are Sorted

The simple case

Assume x1x2xnx_1 \leq x_2 \leq \ldots \leq x_n. As xx increases, the optimal line can only move right on the envelope (or stay the same). Why? Lines are sorted by slope on the envelope. A line with smaller slope beats others for small xx. As xx grows, lines with larger slopes take over.

Once a line stops being optimal, it never comes back. This monotonicity means you never revisit old lines. A simple pointer suffices. Even simpler: use a deque.