Matrix-chain multiplication
◈ 4 cardsParenthesization as a DP over chain length: the min-over-split recurrence, Θ(n³) time, fill-by-length order.
The problem
Matrix multiplication is associative — — so the result never changes, but the cost can change wildly. Multiplying a matrix by a matrix costs scalar multiplications. Given a chain where is , find the parenthesization that minimizes total scalar multiplications.
Brute force is hopeless: the number of parenthesizations grows like (the Catalan numbers).
Optimal substructure
Any parenthesization of splits at some into . By cut-and-paste, both halves must themselves be optimally parenthesized. Let be the minimum cost for :
The extra term is the cost of the final multiply of the two sub-products (a result times a result).
Fill order is by CHAIN LENGTH, not by index
Computing needs and , which both cover shorter chains. So fill in order of increasing chain length — never by raw index. This is the reverse-topological order of the subproblem graph.
Worked example
Six matrices with dimension vector (so is , …, is ). Filling by chain length gives scalar multiplications, achieved by — versus 120 750+ for a bad order on the same chain. Store a split table alongside to reconstruct the parenthesization via PRINT-OPTIMAL-PARENS.
Cost
subproblems (pairs ), up to split choices each time, space.