Sub topic 15
Knuth's Optimization: From O(n^3) to O(n^2)
This chapter assumes you already know the stone-merging recurrence and why plain interval DP costs O(n^3). In that recurrence, each of the O(n^2) intervals tries every split point k, and each try is O(1). Knuth's optimization keeps the same recurrence and the same table. It only narrows the range of k that each interval has to search.
The Shape the Recurrence Must Have
Knuth's optimization applies to recurrences of this form:
dp[i][j] = min over i ≤ k < j of (dp[i][k] + dp[k+1][j]) + w(i, j)
The extra cost w(i, j) depends only on the interval. It must not depend on k. Stone merging fits, because w(i, j) is the total weight of piles i..j. You get that total from prefix sums.
The cost w also has to satisfy two conditions for all a ≤ b ≤ c ≤ d:
| Condition | Inequality | Plain meaning |
|---|---|---|
| Quadrangle inequality | w(a, c) + w(b, d) ≤ w(a, d) + w(b, c) | Two overlapping intervals cost no more than the outer and inner intervals together |
| Monotonicity | w(b, c) ≤ w(a, d) | A contained interval never costs more than the interval that contains it |
Interval sums of non-negative weights meet both conditions. For the quadrangle inequality they meet it with equality.
The Key Fact: Split Points Are Monotone
Let opt[i][j] be the split point that achieves the minimum for interval i..j. When both conditions hold, the optimal splits are ordered:
opt[i][j-1] ≤ opt[i][j] ≤ opt[i+1][j]
Adding an element on the right never moves the best split to the left. Removing an element on the left never moves it to the right. Both neighbors are shorter intervals, so the table has already computed them by the time you reach dp[i][j].
Why the Total Becomes O(n^2)
One interval can still scan a long window. The savings show up when you sum over all intervals of the same length L. Interval i scans opt[i+1][j] − opt[i][j−1] + 1 values. Interval i+1 has j+1 as its right end, and its lower bound is opt[i+1][j], which is exactly the upper bound of interval i. Because each upper bound cancels the next interval's lower bound, the sum telescopes to at most n plus the number of intervals. That gives O(n) work per length and O(n^2) work over all lengths.
Implementation
import random
def min_merge_cost_plain(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]
print(min_merge_cost_knuth([4, 1, 1, 4])) # 18
for _ in range(500):
piles = [random.randint(0, 20) for _ in range(random.randint(0, 12))]
assert min_merge_cost_knuth(piles) == min_merge_cost_plain(piles)
print("all random tests passed")The clamp min(opt[i + 1][j], j - 1) keeps k below j, so the right part k+1..j is never empty. Setting opt[i][i] = i seeds the length-2 windows, and each of those windows contains exactly one split.
Common Errors
- Using the optimization when the cost depends on k. Matrix chain's cost dims[i]·dims[k+1]·dims[j+1] changes with k, so the standard conditions on w(i, j) do not apply to it.
- Breaking ties inconsistently. Use strict
<throughout so opt always records the leftmost best split. This keeps the windows nested the way the proof assumes. - Filling the table in an order other than increasing length. opt[i+1][j] must already exist when interval i..j is processed.
Exercise
For n = 6 and interval length L = 3, the windows are [opt[i][j-1], opt[i+1][j]] for i = 0..3. Write the sum of window sizes and show why it is at most (n - L + 1) + (n - 1).
Show answer
The sum is Σ (opt[i+1][i+2] − opt[i][i+1] + 1) for i = 0..3. Each upper bound opt[i+1][i+2] cancels the next term's lower bound, so the sum telescopes to opt[4][5] − opt[0][1] + 4. Every opt value lies in [0, n−1], so the difference is at most 5. The total is at most 5 + 4 = 9, which is O(n) for this length.
Exercise
Can you apply Knuth's optimization directly to matrix chain multiplication with the recurrence from this tutorial? Why or why not?
Show answer
Not directly. Its added cost dims[i]·dims[k+1]·dims[j+1] depends on the split k, so the recurrence is not of the form dp[i][k] + dp[k+1][j] + w(i, j). The quadrangle-inequality argument assumes that form. Matrix chain has its own faster algorithm, Hu–Shing, which runs in O(n log n).