Memra

Matrix-chain multiplication

◈ 4 cards

Parenthesization 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.

m[i,j]j=1j=2j=3j=4i=101575078759375i=2-026254375i=3--0750i=4---0Highlighted = chain length 2, filled first.
The top-left corner of the m table for p = 30, 35, 15, 5, 10, 20, 25. Only i <= j exists — the dashes are cells the recurrence never defines. The highlighted diagonal is chain length 2 and must be filled first; length 3 (7875, 4375) reads from it, and length 4 (9375) reads from both.
A1..A6m=15125, k=3A1..A3m=7875, k=1A1A2A3m=2625A2A3A4..A6m=3500, k=5A4A5m=1000A4A5A6
The answer the s table reconstructs: ((A1(A2A3))((A4A5)A6)). Each internal node is one multiply, labelled with the m cost of the subchain it produces. The root splits at k = 3, and 7875 + 3500 + 30 x 5 x 25 = 15125 — the recurrence, read straight off the tree.
NORMAL ~/memra/learn/comp-372/matrix-chain-multiplication utf-8 LF