Speeding Up Dynamic Programming
Monotone queues, convex hulls and quadrangle inequalities.
Split 100,000 numbers into groups, where a group with sum costs . The dynamic program is one line: try every place where the last group could start. That is transitions, far over any time limit. Read each candidate as a straight line, and the same program runs as 100,000 deque operations in milliseconds. Every speedup in this lesson works this way: the transition is a minimum over many earlier states, and structure in the cost lets you skip most of them.
What you’ll learn
- Identify the minimum over earlier states as the bottleneck of a DP, and match the structure of its cost to a speedup: a monotone deque, the convex hull trick, divide-and-conquer optimization, Knuth's optimization or the Aliens trick.
- Rewrite a transition as a minimum of lines and implement the monotone convex hull trick in , with an overflow-safe intersection test.
- State the quadrangle inequality, the monotone optimal split points it implies, and the before and after complexity of divide-and-conquer and Knuth's optimization.
- Remove an "exactly groups" constraint with a penalty per group and a binary search, and say when this is exact.
- Recognize which speedup a problem needs, and the look-alikes that need none.
Where the time goes
Many dynamic programs end in a minimum over earlier states:
With states and up to candidates each, that costs . Building layers from costs , and an interval DP that tries every split point costs . The speedups in this lesson keep the states and the values; they change only how the best is found, by exploiting structure in the cost .
The running example: split an array of positive numbers into consecutive groups, where a group with sum costs . The squares punish big groups and the constant punishes many groups. With prefix sums , , and the last group (inclusive):
| Transition | Structure it needs | Technique | Time |
|---|---|---|---|
| window ends that never move left | monotone deque | ||
| slopes and queries both monotone | convex hull trick with a deque | ||
| the same, in any order | none beyond the lines | binary search on the hull, or a Li Chao tree | |
| satisfies the quadrangle inequality | divide-and-conquer optimization | ||
| quadrangle inequality and monotone | Knuth's optimization | ||
| exactly groups | optimal cost convex in | Aliens trick: a penalty per group |
The convex hull trick
Expand the square in the running example:
Each earlier state is a line , and needs the lowest line at . The lowest line at each traces the lower envelope, a concave piecewise-linear curve on which each line occupies at most one interval, in order of decreasing slope. The values are positive, so increases: lines arrive with decreasing slopes, and queries come with increasing .
Two lines meet where :
Both denominators are positive because slopes decrease, so cross-multiplying keeps the inequality's direction:
With values up to , reaches , intercepts reach about and slope gaps , so the products approach , far past . Multiply in 128 bits.
#include <cstdio>
#include <deque>
#include <vector>
using namespace std;
typedef long long ll;
struct Line {
ll m, b; // y = m*x + b
ll at(ll x) const { return m * x + b; }
};
// With slopes m1 > m2 > m3, l2 is useless if l3 overtakes l1 no later than l2 does
bool useless(const Line& l1, const Line& l2, const Line& l3) {
return (__int128)(l3.b - l1.b) * (l1.m - l2.m) <= (__int128)(l2.b - l1.b) * (l1.m - l3.m);
}
int main() {
int n; ll C; // n positive values; a group costs (sum)^2 + C
scanf("%d %lld", &n, &C);
vector<ll> P(n + 1, 0), dp(n + 1, 0);
for (int i = 0; i < n; i++) { ll a; scanf("%lld", &a); P[i + 1] = P[i] + a; }
deque<Line> hull = {{0, 0}}; // the line of j = 0
for (int i = 1; i <= n; i++) {
ll x = P[i]; // queries increase
while (hull.size() >= 2 && hull[1].at(x) <= hull[0].at(x)) hull.pop_front();
dp[i] = hull[0].at(x) + x * x + C;
Line l = {-2 * P[i], dp[i] + P[i] * P[i]}; // slopes decrease
while (hull.size() >= 2 && useless(hull[hull.size() - 2], hull.back(), l)) hull.pop_back();
hull.push_back(l);
}
printf("%lld\n", dp[n]);
} time. On input 8 30 and 3 1 4 1 5 9 2 6 it prints 361. __int128 is a GCC and Clang extension; elsewhere compare in long double and accept a small rounding risk. For maxima instead of minima, negate the lines.
Which transition is a minimum of lines evaluated at a single query point, ready for the convex hull trick?
Show the answer
B.
State contributes the line with slope and intercept , evaluated at . The cost splits into a factor depending only on times a factor depending only on , plus terms in alone or alone.
Monotone split points: divide and conquer, and Knuth
Let be the smallest that achieves the minimum for state . In many DPs it never decreases: the best last group of a longer prefix starts no earlier. The classic sufficient condition is the quadrangle inequality on the cost,
two overlapping intervals cost no more than the outer one plus the inner one. The running example satisfies it, because when increases.
Divide-and-conquer optimization builds layer from . Compute the middle state of a range by scanning all its candidates; then every state to its left needs only candidates up to , and every state to its right only candidates from on. Each level of the recursion scans candidates in total, so a layer costs .
INF = float('inf')
def layer(prev, cost, n): # cur[i] = min over 0 <= j < i of prev[j] + cost(j, i)
cur = [INF] * (n + 1)
def solve(lo, hi, optlo, opthi): # fill cur[lo..hi]; their best j lies in [optlo, opthi]
if lo > hi:
return
mid = (lo + hi) // 2
best, arg = INF, optlo
for j in range(optlo, min(mid - 1, opthi) + 1):
v = prev[j] + cost(j, mid)
if v < best: # strict: keep the smallest best j
best, arg = v, j
cur[mid] = best
solve(lo, mid - 1, optlo, arg)
solve(mid + 1, hi, arg, opthi)
solve(1, n, 0, n - 1)
return cur evaluations of cost per layer and recursion depth . Starting from prev = [0, inf, ..., inf] (zero groups cover only the empty prefix), calls give the best partition of into exactly groups in .
Knuth's optimization handles interval DPs that try every split point, such as merging adjacent piles at a cost equal to the merged size, or building an optimal binary search tree. If satisfies the quadrangle inequality and is monotone under inclusion ( whenever ), the largest optimal splits obey , so each interval tries only the splits between its two neighbors' optima.
The interval tries splits. Sum along one diagonal of the table, all intervals of length :
The first term for cancels the second term for , so the sum telescopes:
There are diagonals, so the whole table costs instead of : a factor of saved, by amortization along each diagonal rather than per interval.
Divide-and-conquer optimization relies on satisfying the quadrangle inequality. When can that fail?
- When is not a power of two
- When the values are large
- When some values are negative, so that is not monotone
- Never: squared differences always satisfy it
Show the answer
C. When some values are negative, so that is not monotone
The gap is non-negative when never decreases. With negative values the two differences can have opposite signs, and the optimal split points need not be monotone. The convex hull trick still applies, because it uses only the algebraic form, but with slopes and queries out of order it needs a Li Chao tree.
Exactly k groups: the Aliens trick
Now demand exactly groups and drop the constant: let be the least total of squared group sums over partitions into consecutive groups. The layered DP costs , or with divide and conquer, too slow when is large as well. Instead, remove the constraint: charge a penalty per group and solve the unconstrained problem
That is the running example with : with the convex hull trick. A larger penalty favors fewer groups, so binary search for a at which an optimum uses groups, and read off . This is Lagrangian relaxation of the count constraint; contest programmers call it the Aliens trick, after a task at the 2016 International Olympiad in Informatics that made it popular.
Always a lower bound. For every and , , hence
Equality when is optimal for . If some optimal partition of the penalized problem has exactly groups, its cost is and
Convexity makes every optimal for some . If for all , the drops shrink as grows. For between the drops on either side of , adding a group beyond saves at most and removing one costs at least :
Which costs make convex? The quadrangle inequality again: the Optimal lesson Divide-and-Conquer Optimization & the Aliens Trick proves that it implies , by exchanging the tails of two partitions. The total cost is , where is the time of one penalized DP and the range of ; here , about 54 halvings for .
Recognizing it
Signals in a problem statement and its constraints:
- an obvious , or DP with around (or for ), well past the rule of thumb of about simple operations per second;
- a cost of the form plus separate terms, often from expanding a square: lines, so the convex hull trick;
- "split into consecutive groups" with a cost that grows faster than linearly with the group (squares of sums, distances to a center): the quadrangle inequality, so divide and conquer or Knuth;
- "exactly groups" with up to : the Aliens trick, if the cost is convex in ;
- a window constraint such as "at most steps back": the monotone deque.
| Problem (in brief) | Transition | Speedup | Cost |
|---|---|---|---|
| A frog jumps at most stones ahead; minimize the landing costs | monotone deque | ||
| Split an array into groups costing | lines at | convex hull trick | |
| Buy rectangular plots in groups costing (widest) × (tallest) | after sorting and pruning: | convex hull trick | , for the sort |
| Merge adjacent piles into one, paying each merged pile's size | interval DP over split points | Knuth's optimization | |
| Place post offices among houses on a line | layered DP; a group costs its distances to its median | divide and conquer, or the Aliens trick | , or |
Key takeaways
- Most slow DPs spend their time in a minimum over earlier states; the speedups keep the states and find the best candidate faster by exploiting structure in the cost.
- If the cost factors as (term in ) × (term in ) plus separate terms, each candidate is a line and the minimum is a lower envelope: with a deque when slopes and queries are monotone, otherwise.
- The quadrangle inequality makes optimal split points monotone: divide and conquer computes a layer in , and Knuth's windows make interval DP by telescoping.
- "Exactly " constraints with a cost convex in become a penalty per group, a binary search on , and the answer , with consistent tie-breaking.
- Stress test every speedup against the plain DP: a violated condition does not crash, it gives wrong answers.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the monotone convex hull trick, a query at pops the front line once the second line is no higher at . Why may that line be discarded for good?
- Because every line is used by exactly one query
- Because the front line has the larger slope, two lines cross at most once, and later queries have larger , so the second line stays at least as low
- Because the deque is sorted by intercept
- It may not: a later query can need it again, so it must be re-inserted
Show the answer
B. Because the front line has the larger slope, two lines cross at most once, and later queries have larger , so the second line stays at least as low
For , the difference increases with , so once the second line is no higher, it stays no higher for every larger . That is why the queries must be monotone; for queries in any order, binary search over the hull instead of popping.
With Knuth's optimization, interval tries only the splits from to . What is the total running time for piles?
- , since one interval can still try splits
Show the answer
C.
One interval may still try many splits, but along each diagonal the windows telescope to at most splits in total, and there are diagonals.
The penalized DP with per group has optimal value , and with consistent tie-breaking the binary search shows that is right for groups. What is the least cost with exactly 4 groups?
- 250
- 278
- 222
Show the answer
C. 222
includes the penalty for the groups, so .
Which problem is best solved by binary search on the answer rather than by a DP speedup?
- Split an array into consecutive groups minimizing the sum of squared group sums
- Split an array into consecutive groups minimizing the largest group sum
- Merge adjacent piles into one at minimum total cost
- Place post offices among houses on a line, minimizing the total distance
Show the answer
B. Split an array into consecutive groups minimizing the largest group sum
For a bottleneck objective, "can every group stay at most ?" is answered by a greedy scan and is monotone in , so binary search over finds the optimum in . The others add up costs over the groups and need the DP, sped up by divide and conquer or the Aliens trick, Knuth, and divide and conquer respectively.
Go deeper
- The Convex Hull Trick & Li Chao Trees · When transitions are lines: the minimum of many lines in O(log n).
- Knuth’s Optimization & Monge Arrays · Quadrangle inequalities, totally monotone matrices and SMAWK.
- Divide-and-Conquer Optimization & the Aliens Trick · Monotone optimal split points, and Lagrangian relaxation of a count constraint.
Further reading
- D. E. Knuth, "Optimum binary search trees," Acta Informatica 1 (1971).
- F. F. Yao, "Efficient dynamic programming using quadrangle inequalities," Proceedings of the 12th ACM Symposium on Theory of Computing (1980).
- CP-Algorithms: "Convex hull trick and Li Chao tree", "Divide and Conquer DP" and "Knuth's Optimization".
- A. Aggarwal, B. Schieber & T. Tokuyama, "Finding a minimum-weight k-link path in graphs with the concave Monge property and applications," Discrete & Computational Geometry 12 (1994).