3.7.13Algorithm Paradigms

DP problems — matrix chain multiplication

1,682 words8 min readdifficulty · medium

WHAT is the problem?

WHY the dimension array? Because the contents of the matrices don't matter — only the cost does, and cost depends only on dimensions.


WHY does parenthesization matter? (worked motivation)

Take A1(10×100), A2(100×5), A3(5×50)A_1(10\times 100),\ A_2(100\times 5),\ A_3(5\times 50), i.e. p=[10,100,5,50]p=[10,100,5,50].

  • (A1A2)A3(A_1A_2)A_3: 101005+10550=5000+2500=750010\cdot100\cdot5 + 10\cdot5\cdot50 = 5000 + 2500 = \mathbf{7500}
  • A1(A2A3)A_1(A_2A_3): 100550+1010050=25000+50000=75000100\cdot5\cdot50 + 10\cdot100\cdot50 = 25000 + 50000 = \mathbf{75000}

HOW to derive the recurrence (from scratch)

Key insight: Any full parenthesization of AiAjA_i\cdots A_j has a last multiplication. That last multiply splits the chain at some point kk: (AiAk)(Ak+1Aj)(A_i\cdots A_k)\,(A_{k+1}\cdots A_j)

  • The left block produces a pi1×pkp_{i-1}\times p_k matrix.
  • The right block produces a pk×pjp_k\times p_j matrix.
  • Combining them costs pi1pkpjp_{i-1}\,p_k\,p_j.

WHY this decomposition works: every parenthesization has exactly one outermost split. If we knew the best split kk, the subproblems "best cost of left" and "best cost of right" are independent — this is optimal substructure.

Let m[i][j]m[i][j] = minimum cost to multiply AiAjA_i\cdots A_j.


Figure — DP problems — matrix chain multiplication

Bottom-up algorithm

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

Full worked example

Matrices with p=[30,35,15,5,10]p=[30,35,15,5,10]A1(30×35),A2(35×15),A3(15×5),A4(5×10)A_1(30\times35), A_2(35\times15), A_3(15\times5), A_4(5\times10), so n=4n=4.

Length 2 chains (cost of pairs):

  • m[1][2]=p0p1p2=303515=15750m[1][2]=p_0p_1p_2=30\cdot35\cdot15=15750Why? only one split k=1k=1.
  • m[2][3]=35155=2625m[2][3]=35\cdot15\cdot5=2625
  • m[3][4]=15510=750m[3][4]=15\cdot5\cdot10=750

Length 3 chains:

  • m[1][3]=min{k=1:m[1][1]+m[2][3]+p0p1p3=0+2625+30355=2625+5250=7875k=2:m[1][2]+m[3][3]+p0p2p3=15750+0+30155=15750+2250=18000=7875 (k=1)m[1][3]=\min\begin{cases}k{=}1: m[1][1]+m[2][3]+p_0p_1p_3=0+2625+30\cdot35\cdot5=2625+5250=7875\\ k{=}2: m[1][2]+m[3][3]+p_0p_2p_3=15750+0+30\cdot15\cdot5=15750+2250=18000\end{cases}=\mathbf{7875}\ (k{=}1)

    Why this step? We compare splitting after A1A_1 vs after A2A_2; the cheaper is splitting at k=1k=1.

  • m[2][4]=min{k=2:0+750+351510=750+5250=6000k=3:2625+0+35510=2625+1750=4375=4375 (k=3)m[2][4]=\min\begin{cases}k{=}2: 0+750+35\cdot15\cdot10=750+5250=6000\\ k{=}3: 2625+0+35\cdot5\cdot10=2625+1750=4375\end{cases}=\mathbf{4375}\ (k{=}3)

Length 4 chain (the answer): m[1][4]=min{k=1:m[1][1]+m[2][4]+p0p1p4=0+4375+303510=4375+10500=14875k=2:m[1][2]+m[3][4]+p0p2p4=15750+750+301510=16500+4500=21000k=3:m[1][3]+m[4][4]+p0p3p4=7875+0+30510=7875+1500=9375m[1][4]=\min\begin{cases}k{=}1: m[1][1]+m[2][4]+p_0p_1p_4=0+4375+30\cdot35\cdot10=4375+10500=14875\\ k{=}2: m[1][2]+m[3][4]+p_0p_2p_4=15750+750+30\cdot15\cdot10=16500+4500=21000\\ k{=}3: m[1][3]+m[4][4]+p_0p_3p_4=7875+0+30\cdot5\cdot10=7875+1500=9375\end{cases} =9375(k=3)=\mathbf{9375}\quad (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.


Flashcards

What does matrix AiA_i's dimension equal in MCM convention?
pi1×pip_{i-1}\times p_i, using the dimension array p[0..n]p[0..n].
What is the cost of multiplying an a×ba\times b by a b×cb\times c matrix?
abca\cdot b\cdot c scalar multiplications.
State the MCM recurrence.
m[i][j]=minik<j(m[i][k]+m[k+1][j]+pi1pkpj)m[i][j]=\min_{i\le k<j}(m[i][k]+m[k+1][j]+p_{i-1}p_k p_j), with m[i][i]=0m[i][i]=0.
Why try all split points kk?
We don't know the optimal last multiplication; greedy fails, so try all and take the min (optimal substructure + overlapping subproblems).
What order do we fill the DP table?
By increasing chain length L=ji+1L=j-i+1 (length 2 up to nn), not row by row.
Time and space complexity of MCM DP?
Time O(n3)O(n^3) (loops over L, i, k), space O(n2)O(n^2).
What is the cost of A1(10×100),A2(100×5),A3(5×50)A_1(10\times100),A_2(100\times5),A_3(5\times50) as (A1A2)A3(A_1A_2)A_3 vs A1(A2A3)A_1(A_2A_3)?
7500 vs 75000 — same result, 10× difference.
How do you recover the actual parenthesization?
Store split point s[i][j]=ks[i][j]=k, then recurse on [i,k][i,k] and [k+1,j][k+1,j].
Why does parenthesization not change the result matrix?
Matrix multiplication is associative.
What is the base case and why?
m[i][i]=0m[i][i]=0 because a single matrix needs no multiplication.

Connections

  • Dynamic Programming — optimal substructure + overlapping subproblems
  • Catalan Numbers — counts the parenthesizations Cn1C_{n-1}
  • Optimal Binary Search Tree — same "try every root/split" interval-DP pattern
  • Burst Balloons — interval DP where you fix the last element
  • Memoization vs Tabulation
  • Time Complexity AnalysisO(n3)O(n^3) from three nested loops

Concept Map

is

same result

goal

Ai is pi-1 x pi

needs

split at k

combine cost

leads to

base case

min over k

solve via

avoids

Matrix chain product

Associative

Cost varies by parenthesization

Minimize scalar multiplications

Dimension array p

Cost of one multiply a*b*c

Optimal substructure

Left block and right block

MCM recurrence m i j

m i i equals 0

Overlapping subproblems

Bottom-up DP by chain length L

Catalan exponential blowup

Hinglish (regional understanding)

Intuition Hinglish mein samjho

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×ba\times b ko b×cb\times c se multiply karne ka cost hota hai abca\cdot b\cdot c. Bas yahi cost minimize karna hai.

Trick ye hai ki tum last multiplication pe socho. Poora chain AiAjA_i \dots A_j ka last multiply kahin na kahin par split hota hai, point kk pe: left part banao, right part banao, phir dono ko jodo. Jodne ka cost pi1pkpjp_{i-1}\,p_k\,p_j. Humein nahi pata best kk kaunsa hai, isliye saare kk try karo aur minimum lo. Yahi recurrence hai: m[i][j]=mink(m[i][k]+m[k+1][j]+pi1pkpj)m[i][j]=\min_k(m[i][k]+m[k+1][j]+p_{i-1}p_k p_j), aur single matrix ka cost 00.

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)O(n^3) aati hai (L, i, k teen loops), space O(n2)O(n^2).

Yaad rakhne ka jugaad: "Last cut, all spots, pi1pkpjp_{i-1}p_k p_j." Aur split point ko s[i][j]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.

Go deeper — visual, from zero

Test yourself — Algorithm Paradigms

Connections