Solve optimal matrix chain multiplication using dynamic programming. Construct a table m[i,j] for minimum scalar multiplications and reconstruct the optimal parenthesization from the s[i,j] split table.
Assistant
Explaining matrix chain multiplication DP and reconstruction
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The dynamic programming algorithm computes the minimal scalar multiplication cost by filling a table of subchain costs diagonally by increasing chain length. It stores split points in a separate table to reconstruct the optimal parenthesization recursively. An example with dimensions [30,35,15,5,10,20,25] yields cost 15125 and parenthesization ((A1(A2A3))((A4A5)A6)).
If you have a chain of (n) matrices
[
A_1\in\mathbb{R}^{p_0\times p_1},;
A_2\in\mathbb{R}^{p_1\times p_2},;
\ldots,;
A_n\in\mathbb{R}^{p_{n-1}\times p_n}
]
then any full parenthesisation corresponds to choosing, for each subchain (A_i\cdots A_j), an index (k) at which to split it into ((A_i\cdots A_k)(A_{k+1}\cdots A_j)). The minimal number of scalar multiplications (m[i,j]) for the subchain (i\ldots j) satisfies the recurrence
[
m[i,i]=0,\qquad
m[i,j]=\min_{i\leq k<j},\bigl(m[i,k]+m[k+1,j]+p_{i-1},p_k,p_j\bigr)\quad\text{for }i<j,
]
and you can remember which (k) attained the minimum in a second table (s[i,j]).
A standard dynamic‑programming routine fills these two tables for increasing chain lengths:
def matrix_chain_order(p):
n = len(p) - 1 # number of matrices
m = [[0]* (n+1) for _ in range(n+1)]
s = [[0]* (n+1) for _ in range(n+1)]
for L in range(2, n+1): # L = chain length
for i in range(1, n-L+2):
j = i + L - 1
m[i][j] = float('inf')
for k in range(i, j):
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
if q < m[i][j]:
m[i][j] = q
s[i][j] = k
return m, s
Once you have filled s, you can reconstruct the optimal parenthesisation with a simple recursive printer:
def print_optimal_parens(s, i, j):
if i == j:
return f"A{i}"
else:
k = s[i][j]
left = print_optimal_parens(s, i, k)
right = print_optimal_parens(s, k+1, j)
return f"({left}{right})"
For example, for the classic dimensions (p=[30,35,15,5,10,20,25]) (six matrices), running the above yields (m[1,6]=15125) as the minimum number of scalar multiplications and the split table (s) indicates the optimal parenthesisation
[
\bigl(A_1 (A_2 A_3)\bigr),\bigl((A_4 A_5),A_6\bigr).
]
The general method is the same for any sequence of dimensions: fill the (m) table bottom‑up, remember the best split (k) in (s), and then recursively apply those splits to print the optimal way to multiply the chain.