Sub topic 15
Knuth's Optimization: From O(n^3) to O(n^2)
This chapter assumes you already know the stone-merging recurrence, the habit of filling the table by increasing interval length, prefix sums for interval costs, and the O(n^3) complexity argument from earlier chapters. Knuth's optimization does not change the recurrence. It narrows which split points k you try for each interval. For a specific family of cost functions, that narrowing provably keeps the answer the same and cuts the total running time to O(n^2).
The Recurrence Shape Knuth's Optimization Targets
The technique applies only to recurrences of this exact form:
dp[i][i] = 0
dp[i][j] = min over i <= k < j of ( dp[i][k] + dp[k+1][j] ) + w(i, j)The added cost w(i, j) depends only on the interval, not on the split k. Stone merging fits this form. There, w(i, j) is the total weight of piles i..j, which prefix sums return in O(1).
Matrix chain multiplication does not fit. Its added cost, dims[i] * dims[k+1] * dims[j+1], depends on k, so the theory below says nothing about it. Burst balloons also has a k-dependent gain. When the shape doesn't match, the optimization isn't valid. It can still happen to produce correct answers on some inputs, and that luck is what makes it dangerous.
The Two Conditions on w
Let opt[i][j] be the split point that achieves the minimum for interval [i, j]. Knuth's result, later generalized by Yao, says that if w satisfies both conditions below, then the optimal split points are monotone.
| Condition | Statement (for all a ≤ b ≤ c ≤ d) | Meaning |
|---|---|---|
| Quadrangle inequality (QI) | w(a, c) + w(b, d) ≤ w(a, d) + w(b, c) | Two overlapping intervals cost no more than the enclosing interval plus the nested one |
| Monotonicity on inclusion | w(b, c) ≤ w(a, d) | A sub-interval never costs more than an interval containing it |
When both hold, the following is true:
opt[i][j-1] <= opt[i][j] <= opt[i+1][j]In words, extending an interval to the right never moves its best split to the left. Shrinking it from the left never moves its best split to the right.
For stone merging, w(i, j) = prefix[j+1] - prefix[i]. The quadrangle inequality holds with equality, because both sides add up the same multiset of piles. Monotonicity holds as long as every pile weight is non-negative. A negative weight breaks monotonicity, and then the guarantee is gone.
Both bounding intervals are one shorter than [i, j], so the length-ordered loop has already computed them. The evaluation order you already use supplies the bounds at no extra cost.
Why the Total Work Becomes O(n^2)
For one interval, the window has opt[i+1][j] - opt[i][j-1] + 1 candidates. That count can be as large as O(n) for a single interval. The savings show up when you add the counts across all intervals of one length L, where j = i + L - 1:
sum over i of ( opt[i+1][i+L-1] - opt[i][i+L-2] + 1 )The differences telescope. The upper bound for row i cancels the lower bound for row i+1. Only opt[n-L+1][n-1] - opt[0][L-2] survives, and that is at most n. Each length therefore costs O(n) in total. With n lengths, the whole table costs O(n^2). Space stays O(n^2) because you now store opt next to dp.
Implementation
def min_merge_cost_knuth(piles):
n = len(piles)
if n <= 1:
return 0
prefix = [0] * (n + 1)
for i, p in enumerate(piles):
prefix[i + 1] = prefix[i] + p
INF = float("inf")
dp = [[0] * n for _ in range(n)]
opt = [[0] * n for _ in range(n)]
for i in range(n):
opt[i][i] = i
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = INF
lo = opt[i][j - 1]
hi = min(opt[i + 1][j], j - 1)
for k in range(lo, hi + 1):
cost = dp[i][k] + dp[k + 1][j]
if cost < dp[i][j]:
dp[i][j] = cost
opt[i][j] = k
dp[i][j] += prefix[j + 1] - prefix[i]
return dp[0][n - 1]
print(min_merge_cost_knuth([4, 1, 1, 4])) # 18Two details carry the correctness.
- Seeding
opt[i][i] = i. For length 2, the window islo = opt[i][i] = iandhi = min(opt[i+1][i+1], j-1) = min(i+1, i) = i. That leaves exactly the one legal split. If you leave the default 0 in the diagonal,lois wrong for everyi > 0. - Clamping
hitoj - 1. A split must leave a non-empty right part, sok = jis illegal.opt[i+1][j]can equalj - 1, which is fine, but the clamp keeps the code safe whatever value the diagonal holds.
A Trace on [4, 1, 1, 4]
The table below shows each interval, its window, and the chosen split. Prefix sums are [0, 4, 5, 6, 10].
| Interval | Window [lo, hi] | Candidates (dp left + dp right) | opt | dp |
|---|---|---|---|---|
| [0,1] | [0, 0] | k=0: 0+0 | 0 | 5 |
| [1,2] | [1, 1] | k=1: 0+0 | 1 | 2 |
| [2,3] | [2, 2] | k=2: 0+0 | 2 | 5 |
| [0,2] | [0, 1] | k=0: 2, k=1: 5 | 0 | 8 |
| [1,3] | [1, 2] | k=1: 5, k=2: 2 | 2 | 8 |
| [0,3] | [0, 2] | k=0: 8, k=1: 10, k=2: 8 | 0 | 18 |
The minimum is 18: merge the two 1s (cost 2), merge 4 with 2 (cost 6), then merge 6 with 4 (cost 10). On an input this small, the windows barely shrink. The gain appears for large n.
Testing Against the Cubic Version
The two conditions are sufficient, not necessary, and errors in the bounds show up as slightly wrong answers rather than crashes. Always keep the O(n^3) version around as a reference, and compare the two on random inputs.
import random
def min_merge_cost(piles):
n = len(piles)
if n <= 1:
return 0
prefix = [0] * (n + 1)
for i, p in enumerate(piles):
prefix[i + 1] = prefix[i] + p
dp = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
best = min(dp[i][k] + dp[k + 1][j] for k in range(i, j))
dp[i][j] = best + prefix[j + 1] - prefix[i]
return dp[0][n - 1]
def min_merge_cost_knuth(piles):
n = len(piles)
if n <= 1:
return 0
prefix = [0] * (n + 1)
for i, p in enumerate(piles):
prefix[i + 1] = prefix[i] + p
INF = float("inf")
dp = [[0] * n for _ in range(n)]
opt = [[0] * n for _ in range(n)]
for i in range(n):
opt[i][i] = i
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = INF
lo = opt[i][j - 1]
hi = min(opt[i + 1][j], j - 1)
for k in range(lo, hi + 1):
cost = dp[i][k] + dp[k + 1][j]
if cost < dp[i][j]:
dp[i][j] = cost
opt[i][j] = k
dp[i][j] += prefix[j + 1] - prefix[i]
return dp[0][n - 1]
random.seed(1)
for _ in range(500):
piles = [random.randint(0, 20) for _ in range(random.randint(0, 12))]
assert min_merge_cost(piles) == min_merge_cost_knuth(piles), piles
print("all agree")You can also check the conditions on w directly for small sizes. This is useful when you adapt the method to a new cost function.
from itertools import combinations_with_replacement
def satisfies_knuth_conditions(w, n):
for a, b, c, d in combinations_with_replacement(range(n), 4):
if w(a, c) + w(b, d) > w(a, d) + w(b, c):
return False
if w(b, c) > w(a, d):
return False
return True
weights = [3, 0, 7, 2, 5]
prefix = [0]
for x in weights:
prefix.append(prefix[-1] + x)
print(satisfies_knuth_conditions(lambda i, j: prefix[j + 1] - prefix[i], len(weights))) # True
negative = [3, -4, 7]
prefix = [0]
for x in negative:
prefix.append(prefix[-1] + x)
print(satisfies_knuth_conditions(lambda i, j: prefix[j + 1] - prefix[i], len(negative))) # Falsecombinations_with_replacement yields sorted tuples, so a ≤ b ≤ c ≤ d holds automatically. A brute-force check proves nothing for all n, but it catches a bad cost function quickly.
Common Errors and Decision Criteria
| Symptom or situation | Cause | Fix |
|---|---|---|
| Wrong answers only for some `i > 0` | `opt[i][i]` left at 0 | Seed `opt[i][i] = i` |
| Index error or an empty right part | `hi` not clamped | Use `min(opt[i+1][j], j-1)` |
| Agrees on tests, fails on hidden inputs | `w` depends on `k`, as in matrix chain | Don't apply Knuth; keep O(n^3) or use a problem-specific algorithm |
| Fails when weights can be negative | Monotonicity on inclusion is violated | Fall back to the cubic DP |
| Circular piles | Doubled array of length 2n | Knuth works on the doubled table; fill lengths up to n and seed the full diagonal |
| Top-down memoized code | Windows need the shorter intervals first | Convert to bottom-up by length before optimizing |
Use Knuth's optimization when n reaches a few thousand, where O(n^3) is too slow but O(n^2) memory is still affordable, and when you can show or test that w meets both conditions. For n in the low hundreds, the cubic version is simpler and fast enough.
Exercise
Why can't Knuth's optimization be applied directly to matrix chain multiplication, even though matrix chain also uses a split-point recurrence?
Show answer
Knuth's theorem needs the form dp[i][j] = min_k(dp[i][k] + dp[k+1][j]) + w(i, j), where the added cost depends only on i and j. In matrix chain the added cost dims[i] dims[k+1] dims[j+1] depends on k, so the quadrangle-inequality argument does not apply, and monotonicity of opt is not guaranteed.
Exercise
For a fixed length L, explain why the window sizes across all i add up to at most about 2n, even though a single window can contain O(n) candidates.
Show answer
The window for [i, j] runs from opt[i][j-1] to opt[i+1][j]. Summed over i, each upper bound opt[i+1][i+L-1] cancels the next row's lower bound, so the sum telescopes to opt[n-L+1][n-1] - opt[0][L-2] plus one per interval. That is at most n + n = O(n) per length, and O(n^2) across all n lengths.
Exercise
A teammate initializes opt with zeros and does not set opt[i][i] = i. What is the window for interval [3, 4], and what goes wrong?
Show answer
lo = opt[3][3] = 0 and hi = min(opt[4][4], 3) = 0, so the loop tries only k = 0. That split is outside [3, 4]. The code reads dp[3][0] and dp[1][4], gets a meaningless cost, and records opt[3][4] = 0, which corrupts every longer interval that uses it as a bound.