DP Optimizations
A correct DP recurrence is only half the battle; its naive evaluation is often a factor of slower than necessary. This capstone surveys five techniques, monotonic-queue, the convex hull trick, divide-and-conquer optimization, Knuth's optimization, and SOS DP, that each exploit structure in the transition (a sliding window, linear costs, monotone optimal splits, the quadrangle inequality, or subset lattices) to shave an , , or worse factor off the running time.
╌╌╌╌
The previous lessons built DP recurrences and trusted their dimensions to give the running time: a table of states, each filled by a transition that scans predecessors, costs . Often is itself , a min over all earlier states or a split point ranging over an interval, and the honest recurrence runs in or . The techniques in this lesson all share one move: they observe that the transition is not an arbitrary min over predecessors but one with structure, and they maintain an auxiliary object (a deque, a hull of lines, a monotone split pointer) that answers each transition faster than a fresh scan.1 None of them changes what the DP computes, only how fast it computes it.
A useful test runs through the whole lesson: look at the shape of the inner min/max and ask what stays constant and what slides as the outer index advances. The answer names the technique.
The cost model here is the state-count times transition-work product; these techniques attack the second factor.
Monotonic-queue optimization
Consider a transition of the form
where each state takes a min (or max) of the previous states within a sliding window of width , then adds a term depending only on . Evaluated directly this is : every state rescans its window. But the window's left edge only ever moves right, and its right edge only ever moves right, so this is the sliding-window minimum problem, which a monotonic deque solves in amortized per step.2
- 1empty deque of indicesincreasing frontback
- 2; push onto
- 3for to do
- 4while nonempty and do
- 5pop front ofleft the window
- 6
- 7while nonempty and do
- 8pop back ofdominates older candidate
- 9push onto
Each index is pushed and popped at most once, so the total work is , down from . Jump Game VI is the canonical instance: is the best score reachable at index , equal to of for in the last positions, plus : a sliding-window max, the same deque with the inequality flipped. Constrained Subsequence Sum is the same recurrence with and a reset. This is the monotonic-stack idea from the sequences module, extended to a deque so that both ends move.
For a full trace, run Jump Game VI on with jump width , so and . The deque stores indices whose values decrease from front to back; the front is always the window maximum. Each row shows the state after processing index :
| window | front | deque (indices, ) | ||
|---|---|---|---|---|
| — | — | |||
Two evictions do the real work. At index has slid out of the window (), so it is popped from the front; then dominates the stale and at the back, clearing them. At the same back-eviction wipes and , leaving only the fresh maximum. The answer is read straight off, and across all six steps no index is touched more than twice.
Convex hull trick
Now suppose each previous state contributes a line and the transition queries the best line at a point:
where the slope and intercept depend only on (typically is a function of and the problem data), and depends only on . The naive evaluation is . But over a fixed set of lines, as a function of , is the lower envelope of those lines, a convex, piecewise-linear curve. Only the lines on the lower hull can ever be optimal; the rest are dominated everywhere. Maintaining that hull and querying it is the Convex Hull Trick.1
If lines are inserted in monotone slope order and queries are also monotone, both operations are amortized: push lines onto a stack-like hull, popping any that the newcomer makes redundant, and advance a pointer for queries. Without monotonicity, store the hull and binary-search for the optimal line at in , or use a Li Chao tree. Either way the DP drops from to .
For example, suppose three previous states have contributed the lines , , and (slopes , , ). Their lower envelope, the pointwise minimum, is a convex shape. Checking crossings, at , where both equal . But the flat line already sits below that meeting point, so and never touch the envelope near their crossing: undercuts both. Solving gives and gives , so the envelope is on , then on , then on — all three lines survive on the hull. For a query the naive scan evaluates all three (, , ) and takes the min, . With monotone queries the hull instead advances a pointer to the segment and reads in , never re-checking or . Had been instead, the two crossings would invert ( at , at ) and would be dominated everywhere; inserting it would find it already redundant and pop it, leaving the two-line hull meeting at .
Divide-and-conquer optimization
For a layered transition
let be the smallest achieving that minimum. If is monotone in (that is, for every fixed layer ), then the search range for column is bounded by the answers of its neighbors, and we can solve a whole layer by divide and conquer:
- 1if then return
- 2
- 3;
- 4for to do
- 5if then
- 6;
- 7
- 8
- 9
Solve the middle column first by scanning its full allowed -range; its optimum then caps the left half's search and floors the right half's, so the two recursive calls split both the columns and the candidate range:
At each recursion depth the -ranges across all sub-calls overlap by at most their endpoints, so one depth costs ; there are depths per layer and layers, giving instead of . The monotonicity of is the hypothesis you must verify; it holds whenever satisfies the quadrangle inequality (below), but is sometimes provable directly from the problem.
Knuth's optimization
Interval DPs have the shape
and naively cost : intervals, each scanning split points. Knuth's optimization applies when satisfies the quadrangle inequality (QI) and is monotone on intervals:
When QI holds, the optimal split point is monotone in both arguments:
So when filling we only scan split points in rather than all of . Summed over a fixed interval length, those ranges telescope, and the total work collapses to . This is the optimization behind optimal binary search trees and the cost-merging part of matrix-chain multiplication from the interval-DP lesson: both have cost functions satisfying QI, so Knuth's optimization applies and each runs in .
SOS DP (sum over subsets)
The last technique is combinatorial rather than geometric. Given a value for every bitmask over bits, we want, for each mask , an aggregate over all of its submasks:
Enumerating every submask of every mask costs (the classic submask-enumeration bound). Sum over subsets does it in by adding one bit-dimension at a time: process bits , and when processing bit , fold each mask that has bit set into the version without it. It is a multidimensional prefix sum over the hypercube .
- 1for to do
- 2
- 3for to do
- 4for to do
- 5if then
- 6
After processing bit , holds the sum of over all submasks of that differ from only in bits ; after all bits, it is the full submask sum. To see the fold in motion, take with indexed by masks . The array starts as a copy of and absorbs one axis per pass:
| after | ||||||||
|---|---|---|---|---|---|---|---|---|
| init | ||||||||
| bit | ||||||||
| bit | ||||||||
| bit |
The final row is the submask sum. Check (all eight submasks) and , both matching the table — computed in additions rather than the of naive submask enumeration, a gap that widens fast: at it is against .
Replacing the order of the two loops, or flipping the bit test, gives sums over supersets instead. This is what drives the bitmask-DP lesson's harder counting problems: anything that asks you to aggregate over all subsets of every state at once.
Choosing the technique
| Technique | Transition shape | Complexity win |
|---|---|---|
| Monotonic queue | (sliding window) | |
| Convex hull trick | (line per state) | |
| Divide & conquer | , monotone | |
| Knuth | , QI | |
| SOS DP | (submask aggregate) |
The origins of the speedups
Each technique here has a traceable pedigree, and the pedigrees explain why the
conditions are what they are. Knuth's optimization is the oldest: Donald
Knuth's 1971 paper Optimum binary search trees
(Acta Informatica 1) showed
that the dynamic program for optimal BSTs runs in because the
optimal root of the interval lies between the optimal roots of and . F. Frances Yao generalized the mechanism in Efficient dynamic programming using quadrangle inequalities
(1980, STOC) and Speed-up in dynamic programming
(1982, SIAM J. Algebraic Discrete Methods), isolating the
quadrangle inequality as the exact structural hypothesis, which is why the
condition carries her name (the Knuth/Yao QI) and covers matrix-chain and BST
alike.3
The convex hull trick grew out of computational geometry's lower-envelope
machinery rather than a single DP paper; the general offline/online line-container
that supports arbitrary insertion order is the Li Chao tree (attributed to the
competitive-programming author Li Chao), a segment tree over -coordinates that
stores at each node the line best there, answering point queries in
without any slope-monotonicity assumption. Divide-and-conquer optimization is
the algorithmic cousin of the same monotone-optimum idea; it needs only that
be monotone in , a strictly weaker condition than the full QI, which
is why it applies to layered (exactly groups
) partition DPs where Knuth does
not.
Sum-over-subsets is a special case of the fast zeta / Möbius transform over
the subset lattice, the combinatorial analog of the fast Fourier transform for the
Boolean hypercube. Björklund, Husfeldt, Kaski, and Koivisto's work on subset
convolution (Fourier meets Möbius: fast subset convolution
, 2007, STOC) built on
exactly this zeta transform to compute the full subset convolution in
, which in turn cracked several -flavored counting problems and the
graph-coloring polynomial.4 The monotonic-deque idea, meanwhile, is the sliding-window
minimum, folklore since at least the 1980s and standard in streaming and signal
processing (it is the linear-time morphological erosion of a 1-D signal). Modern
competitive programming (see the open cp-algorithms reference) collects all
five together because they answer one question — what structure does the
inner loop have? — with the same discipline the asymptotic-analysis
lesson applies to loops in general.
Takeaways
- These are not new DPs but faster evaluations of an existing recurrence; the trigger is always structure in the inner min/max, not its mere size.
- Monotonic-queue optimization: a sliding-window min/max transition runs in via a monotonic deque whose front is the window optimum — the natural tool for Jump Game VI and Constrained Subsequence Sum.
- Convex hull trick: when each state is a line and the transition queries the lower envelope at , maintain the hull and query in (or amortized when slopes and queries are monotone), turning into .
- Divide-and-conquer optimization needs a monotone optimal split; Knuth's optimization gets that monotonicity for interval DPs from the quadrangle inequality, dropping to on problems like optimal BST and matrix-chain.
- SOS DP aggregates over every submask of every mask in by summing one bit-dimension at a time — a prefix sum over the subset lattice.
- Verify the applicability condition (window monotonicity, linear cost, monotone split, QI) before reaching for the speedup; the optimization is only correct when its structural hypothesis holds.
Footnotes
- Erickson, Ch. — Dynamic Programming: DP optimizations (the convex hull trick, divide-and-conquer, and Knuth's optimization) treated as transition-acceleration techniques over a fixed recurrence; CLRS §15.2/§15.5 for the interval-DP instances (matrix-chain, optimal BST) that Knuth accelerates. ↩ ↩2
- Skiena, § — Dynamic Programming: recognizing that a DP's cost is the product of state count and per-state transition work, and attacking the transition. ↩
- Knuth,
Optimum binary search trees
, Acta Informatica 1 (1971), and F. F. Yao,Speed-up in dynamic programming
, SIAM J. Algebraic Discrete Methods 3 (1982): the optimal-BST algorithm and the quadrangle-inequality generalization behind Knuth's optimization. ↩ - Björklund, Husfeldt, Kaski, Koivisto,
Fourier meets Möbius: fast subset convolution
, STOC 2007: the fast zeta/Möbius transform over the subset lattice () that SOS DP computes, and its use in subset convolution. ↩
╌╌ END ╌╌