Sub topic 3
Choosing a Split Point
This chapter assumes you already know basic dynamic programming (memoization and tabulation), recursion, and Big-O analysis, and that you can read Python. It also assumes the two earlier chapters of this tutorial: dp[i][j] holds the best answer for a contiguous range, and single-element ranges are the base cases.
The split-point recurrence is the most common shape in interval DP. To solve a range, you try every position where the range could be cut into a left part and a right part. You solve each part on its own, add the cost of joining them, and keep the best total.
The Recurrence
Use inclusive bounds, so dp[i][j] covers elements i through j. A split point k divides the range into [i..k] and [k+1..j]:
dp[i][j] = min over k in [i, j-1] of ( dp[i][k] + dp[k+1][j] + join(i, k, j) )The recurrence has three parts:
- The candidate set.
kruns fromitoj - 1. Each value gives two non-empty halves. Ifk = j, the right half[j+1..j]is empty. That is usually meaningless or a silent bug. - The subproblem values.
dp[i][k]anddp[k+1][j]are strictly shorter ranges. That fact is what lets the recursion terminate, and the next chapter uses it to choose a filling order. - The join cost.
join(i, k, j)is what it costs to combine the two finished halves. In matrix chain multiplication it isdims[i] * dims[k+1] * dims[j+1]. When merging piles it is the total weight of the range.
For maximization problems, replace min with max and start from negative infinity instead of positive infinity.
Why Trying Every k Is Enough
The recurrence is correct when two conditions hold.
- Every solution has a top-level split. Any valid way of processing
[i..j]ends with one final step that joins some[i..k]with some[k+1..j]. A full parenthesization of a matrix product has exactly one outermost multiplication. Because the recurrence tries everyk, it considers the true final split of the optimal solution. - The halves are independent. Once
kis fixed, the best way to handle the left half does not depend on how the right half is handled. The join cost also depends only on(i, k, j), not on the internal structure of either half.
Together these conditions give optimal substructure. Fix the optimal solution's top split k*. Its left part must be an optimal solution for [i..k*]. If it were not, you could swap in a cheaper one without changing the join cost, and the total would drop. That contradicts optimality.
A Generic Implementation
The function below takes the join cost as a parameter. It uses memoized recursion so you can concentrate on the recurrence itself. The next chapter shows how to fill the same table bottom-up.
from functools import lru_cache
def split_dp(n, join):
"""Minimum cost to fully combine elements 0..n-1 using binary splits.
join(i, k, j) is the cost of combining [i..k] with [k+1..j].
"""
if n <= 1:
return 0
@lru_cache(maxsize=None)
def dp(i, j):
if i == j:
return 0
best = float("inf")
for k in range(i, j): # k = i .. j-1, both halves non-empty
cost = dp(i, k) + dp(k + 1, j) + join(i, k, j)
if cost < best:
best = cost
return best
return dp(0, n - 1)
dims = [10, 30, 5, 60]
print(split_dp(3, lambda i, k, j: dims[i] * dims[k + 1] * dims[j + 1])) # 4500
piles = [4, 1, 1, 4]
prefix = [0]
for p in piles:
prefix.append(prefix[-1] + p)
print(split_dp(4, lambda i, k, j: prefix[j + 1] - prefix[i])) # 20The same skeleton solves two different problems. Only the join cost changes. When you meet a new problem, a good first question is: "If I knew the final cut, what would the last step cost?"
Tracing One Interval
Take matrices A0 (10×30), A1 (30×5), and A2 (5×60). The dimension list is [10, 30, 5, 60]. The length-2 ranges are already solved:
dp[0][1] = 10·30·5 = 1500dp[1][2] = 30·5·60 = 9000
Now evaluate dp[0][2]:
| k | Left | Right | Join `dims[0]·dims[k+1]·dims[3]` | Total |
|---|---|---|---|---|
| 0 | `dp[0][0] = 0` | `dp[1][2] = 9000` | 10·30·60 = 18000 | 27000 |
| 1 | `dp[0][1] = 1500` | `dp[2][2] = 0` | 10·5·60 = 3000 | 4500 |
The minimum is 4500 at k = 1, which means (A0 A1) A2. The two choices differ by a factor of six. That is why the order of operations matters and why you must try every split.
Checking Against Brute Force
Each full parenthesization of n items is a binary tree. There are Catalan(n−1) of them, and that count grows roughly like 4^n. The split DP reaches the same answer in polynomial time. A brute-force enumerator makes a good test oracle while you are developing a recurrence:
import random
from functools import lru_cache
def brute_force(i, j, join):
if i == j:
return 0
return min(
brute_force(i, k, join) + brute_force(k + 1, j, join) + join(i, k, j)
for k in range(i, j)
)
def split_dp(n, join):
@lru_cache(maxsize=None)
def dp(i, j):
if i == j:
return 0
return min(dp(i, k) + dp(k + 1, j) + join(i, k, j) for k in range(i, j))
return dp(0, n - 1)
for _ in range(200):
n = random.randint(1, 7)
dims = [random.randint(1, 20) for _ in range(n + 1)]
join = lambda i, k, j, d=dims: d[i] * d[k + 1] * d[j + 1]
assert brute_force(0, n - 1, join) == split_dp(n, join)
print("all tests passed")Both functions use the same recurrence, so this test catches indexing and memoization mistakes. It does not test whether the recurrence models the problem correctly. To check the model, write the brute force directly from the problem statement. For matrices, that means enumerating parenthesizations and multiplying them out.
Inclusive Versus Half-Open Bounds
Some problems read more naturally with half-open ranges [i, j). Matrix chains are one example: matrix m sits between boundaries m and m+1. The recurrence changes in three places:
| Aspect | Inclusive `[i..j]` | Half-open `[i, j)` |
|---|---|---|
| Single element | `i == j` | `j == i + 1` |
| Split range | `k in range(i, j)` | `k in range(i + 1, j)` |
| Subproblems | `dp[i][k]`, `dp[k+1][j]` | `dp[i][k]`, `dp[k][j]` |
| Full answer | `dp[0][n-1]` | `dp[0][n]` |
In the half-open form, k is a shared boundary rather than the last element of the left half. Both forms are correct. Mixing them in one function is a frequent source of bugs.
Common Errors
- Off-by-one in the k loop.
range(i, j + 1)creates an empty right half. Depending on your base case, it reads an uninitialized cell or adds a zero-cost branch. - Uninitialized best value. Starting
bestat0in a minimization problem returns 0 for every range. Start at infinity, or at the first candidate's value. - Join cost that depends on k when it should not. In stone merging the join cost is the range total for every
k. You can add it once after the loop, as long as you understand why that works. - Hidden dependence between halves. If choosing a split on the left changes what is available on the right, the halves are not independent. The recurrence will run without errors and return a wrong number. Test on small inputs against a brute force written from the problem statement.
- Forgetting to record k. If you need the structure as well as the cost, store the best
kfor each range. A later chapter rebuilds the optimal parenthesization from that table.
Exercise
For dimensions [5, 10, 3, 12], compute dp[0][2] for matrix chain multiplication by evaluating each split point, and state which parenthesization wins.
Show answer
dp[0][1] = 5·10·3 = 150 and dp[1][2] = 10·3·12 = 360. For k = 0: 0 + 360 + 5·10·12 = 960. For k = 1: 150 + 0 + 5·3·12 = 330. The minimum is 330 at k = 1, so (A0 A1) A2 wins.
Exercise
A student writes the loop as for k in range(i, j + 1) and makes dp(i, j) return 0 whenever i > j. What goes wrong for matrix chains?
Show answer
The extra split k = j combines dp(i, j) itself with the empty range dp(j+1, j) = 0. With memoization, dp(i, j) then calls itself, which recurses forever or reads an unfinished value. Even if that call were avoided, the join term dims[i]·dims[j+1]·dims[j+1] has no meaning. The loop must stop at j - 1.
Exercise
You need the minimum cost to combine a sequence where joining [i..k] with [k+1..j] costs (number of elements on the left) × (number on the right). Write the join function for split_dp, and explain why the split recurrence is valid here.
Show answer
join = lambda i, k, j: (k - i + 1) * (j - k). The cost depends only on i, k, and j, not on how each half was built internally, so the halves are independent. Every full combination also has one final join with some k. Both conditions hold, so the recurrence is exact.