Key insight: Any full parenthesization of Ai⋯Aj has a last multiplication. That last multiply splits the chain at some point k:
(Ai⋯Ak)(Ak+1⋯Aj)
The left block produces a pi−1×pk matrix.
The right block produces a pk×pj matrix.
Combining them costs pi−1pkpj.
WHY this decomposition works: every parenthesization has exactly one outermost split. If we knew the best split k, the subproblems "best cost of left" and "best cost of right" are independent — this is optimal substructure.
MCM(p[0..n]):
n = len(p) - 1 # number of matrices
m = 2D array, m[i][i] = 0
s = 2D array # to reconstruct the splits
for L in 2..n: # chain length
for i in 1..n-L+1:
j = i + L - 1
m[i][j] = +infinity
for k in i..j-1:
cost = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
if cost < m[i][j]:
m[i][j] = cost
s[i][j] = k
return m[1][n], s
Length 4 chain (the answer):m[1][4]=min⎩⎨⎧k=1:m[1][1]+m[2][4]+p0p1p4=0+4375+30⋅35⋅10=4375+10500=14875k=2:m[1][2]+m[3][4]+p0p2p4=15750+750+30⋅15⋅10=16500+4500=21000k=3:m[1][3]+m[4][4]+p0p3p4=7875+0+30⋅5⋅10=7875+1500=9375=9375(k=3)
Recall Feynman: explain to a 12-year-old
Imagine you have to glue together a row of LEGO sheets, two at a time. Joining two sheets takes effort that depends on their sizes. The final big sheet is the same whichever order you glue, but some orders cost way less effort. MCM is just the smart plan: try every spot where you could make the last glue, remember the cheapest way to build each piece, and never re-solve the same piece twice.
Dekho, Matrix Chain Multiplication ka core idea simple hai: jab tum bahut saari matrices ko multiply karte ho, toh answer matrix toh same rehta hai chahe tum kisi bhi order me brackets lagao (kyunki multiplication associative hai). Lekin kitni scalar multiplications lagti hain, woh order pe depend karta hai — aur farak 10x, 100x tak ho sakta hai. Ek a×b ko b×c se multiply karne ka cost hota hai a⋅b⋅c. Bas yahi cost minimize karna hai.
Trick ye hai ki tum last multiplication pe socho. Poora chain Ai…Aj ka last multiply kahin na kahin par split hota hai, point k pe: left part banao, right part banao, phir dono ko jodo. Jodne ka cost pi−1pkpj. Humein nahi pata best k kaunsa hai, isliye saare k try karo aur minimum lo. Yahi recurrence hai: m[i][j]=mink(m[i][k]+m[k+1][j]+pi−1pkpj), aur single matrix ka cost 0.
Greedy mat lagao — "sabse chhota dimension pe cut karo" wala idea galat hai, kyunki abhi sasta lagne wala cut baad me mehnga pad sakta hai. Isliye DP use karte hain. Table ko chain length L ke order me bharo (chhoti chains pehle), kyunki badi chain ko chhoti chains chahiye hoti hain. Time complexity O(n3) aati hai (L, i, k teen loops), space O(n2).
Yaad rakhne ka jugaad: "Last cut, all spots, pi−1pkpj." Aur split point ko s[i][j] me store kar lo taaki actual bracket structure wapas bana sako. Exam aur interview dono me ye classic interval-DP problem hai — Optimal BST aur Burst Balloons bhi isi pattern pe chalte hain.