Sub topic 2
Worked Example: Matrix Chain Multiplication
This chapter assumes you already know the interval state dp[i][j], the split-point recurrence, and filling the table by increasing interval length. You should also be comfortable reading Python.
Matrix Chain Multiplication
Matrix Ai has shape dims[i] x dims[i+1]. Multiplying a p x q matrix by a q x r matrix costs p*q*r scalar multiplications. Matrix multiplication is associative, so the parenthesization does not change the result. It does change the cost.
dp[i][j] is the minimum cost of computing Ai ... Aj (inclusive bounds). The last multiplication in that product splits it at some k, combining (Ai..Ak) with (Ak+1..Aj):
dp[i][j] = min over k in [i, j) of dp[i][k] + dp[k+1][j] + dims[i]*dims[k+1]*dims[j+1]
The base case is dp[i][i] = 0, because a single matrix needs no multiplication.
Recovering the Optimal Parenthesization
The cost alone does not tell you the order of operations. To get the order, record the best k in a split table. Then follow the table recursively from (0, n-1) down to single matrices.
def matrix_chain_order(dims):
n = len(dims) - 1
INF = float("inf")
dp = [[0] * n for _ in range(n)]
split = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = INF
for k in range(i, j):
cost = dp[i][k] + dp[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1]
if cost < dp[i][j]:
dp[i][j] = cost
split[i][j] = k
return dp[0][n - 1], split
def parenthesize(split, i, j):
if i == j:
return f"A{i}"
k = split[i][j]
return "(" + parenthesize(split, i, k) + " " + parenthesize(split, k + 1, j) + ")"
cost, split = matrix_chain_order([10, 30, 5, 60])
print(cost) # 4500
print(parenthesize(split, 0, 2)) # ((A0 A1) A2)The other order, A0 (A1 A2), costs 27000. Choosing the right split makes it six times more expensive to get wrong.
Shrinking from the Ends
Some problems have no split point. Instead, dp[i][j] depends on what happens at the two endpoints. You either use both s[i] and s[j], or you drop one of them and move to dp[i+1][j] or dp[i][j-1]. Each step reads only intervals one or two shorter, so the table costs O(n²) time.
Longest Palindromic Subsequence
def longest_palindromic_subsequence(s):
n = len(s)
if n == 0:
return 0
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return dp[0][n - 1]
print(longest_palindromic_subsequence("bbbab")) # 4When the ends match, they wrap the best palindrome inside them. When they don't match, at least one end must be dropped.
Exercise
For dims = [2, 3, 4, 5], what is the minimum cost and the optimal parenthesization?
Show answer
64, with ((A0 A1) A2): 234 + 245 = 24 + 40. The alternative (A0 (A1 A2)) costs 60 + 30 = 90.
Exercise
What does longestpalindromicsubsequence("cbbd") return, and why?
Show answer
2. The outer characters never match, so the best you can do is "bb".