Purpose: Reduce an interval DP of the form
from to , by restricting the search for the optimal split point.
The Condition
Let be the smallest achieving the minimum. Knuth’s optimization applies when
This monotonicity is guaranteed when the cost function satisfies both:
- Quadrangle inequality (QI): for all .
- Monotonicity on the lattice of intervals: whenever .
In practice, most “merge two adjacent piles, cost = sum of the range” problems satisfy both, and you can verify them by brute force on small before committing.
Algorithm
Iterate by increasing interval length. For each , scan only in and record the argmin.
Code
// dp[i][j] over half-open intervals; C(i,j) is the merge cost
long long solve(int n, function<long long(int,int)> C) {
vector<vector<long long>> dp(n + 1, vector<long long>(n + 1, 0));
vector<vector<int>> opt(n + 1, vector<int>(n + 1, 0));
for (int i = 0; i < n; i++) opt[i][i + 1] = i;
for (int len = 2; len <= n; len++) {
for (int i = 0; i + len <= n; i++) {
int j = i + len;
dp[i][j] = LLONG_MAX;
int lo = opt[i][j - 1], hi = opt[i + 1][j];
for (int k = lo; k <= hi; k++) {
long long cur = dp[i][k] + dp[k][j] + C(i, j);
if (cur < dp[i][j]) { dp[i][j] = cur; opt[i][j] = k; }
}
}
}
return dp[0][n];
}Paradigm
Dynamic programming with a monotone argmin. The same family as divide and conquer DP and SMAWK — all exploit the quadrangle inequality, just with different access patterns.
Complexity
- Time:
- Space:
The telescoping argument: for a fixed interval length, the total work is
and the terms telescope across , leaving per length and overall.
Classic Applications
- Optimal binary search tree (Knuth’s original problem) — the reason it is named after him
- Merging stones / “burning piles” — merge adjacent piles, cost = sum of the merged range
- Optimal file merging, matrix chain-like problems with QI costs
- Hu-Tucker — the alternative for the alphabetic-tree case
When it does not apply
Matrix chain multiplication does not satisfy the quadrangle inequality in general, so it stays . Always test QI on random small inputs before assuming.
Related Optimizations
| Recurrence shape | Technique | Result |
|---|---|---|
| , QI | Knuth | |
| , monotone opt | D&C DP | |
| Row minima of a totally monotone matrix | SMAWK | |
| CHT | / | |
| Fixed-width window minimum | Monotone queue |