# Dynamic Programming Masterclass: 0/1 Knapsack, LCS & Matrix Chain Multiplication
Exam: GATE Computer Science & Information Technology (GATE CS)
Subject: Algorithms
Canonical URL: https://gateandnet.com/exams/gate-cs/algorithms/dynamic-programming-knapsack-lcs-mcm

> Optimal substructure & overlapping subproblems, exact DP recurrences, time/space complexities, and pseudo-polynomial complexity of 0/1 Knapsack.

## 1. Greedy vs Dynamic Programming Decision Matrix

| Classic Problem | Greedy Works? | Optimal Paradigm | Time Complexity | Space |
| :--- | :--- | :--- | :--- | :--- |
| **Fractional Knapsack** | **Yes** (Sort by $v_i / w_i$) | Greedy | $\mathcal{O}(n \log n)$ | $\mathcal{O}(1)$ |
| **0/1 Knapsack** | **No!** | Dynamic Programming | $\Theta(nW)$ (Pseudo-polynomial) | $\mathcal{O}(W)$ |
| **Activity Selection** | **Yes** (Earliest finish time) | Greedy | $\mathcal{O}(n \log n)$ | $\mathcal{O}(1)$ |
| **Huffman Optimal Prefix Code** | **Yes** (Min-Heap merge 2 smallest) | Greedy | $\mathcal{O}(n \log n)$ | $\mathcal{O}(n)$ |
| **Matrix Chain Multiplication** | **No!** | Dynamic Programming | $\Theta(n^3)$ | $\Theta(n^2)$ |
| **Longest Common Subsequence** | **No!** | Dynamic Programming | $\Theta(mn)$ | $\mathcal{O}(\min(m,n))$ |
| **All-Pairs Shortest Path** | — | Floyd-Warshall DP | $\Theta(V^3)$ | $\Theta(V^2)$ |

## 2. Matrix Chain Multiplication Worked Insight

To multiply $A_1 (p_0 \times p_1), A_2 (p_1 \times p_2), A_3 (p_2 \times p_3)$, say $A_1(10 \times 100), A_2(100 \times 5), A_3(5 \times 50)$:
- $((A_1 A_2) A_3)$ costs $(10 \cdot 100 \cdot 5) + (10 \cdot 5 \cdot 50) = 5000 + 2500 = \mathbf{7,500}$ scalar multiplications.
- $(A_1 (A_2 A_3))$ costs $(100 \cdot 5 \cdot 50) + (10 \cdot 100 \cdot 50) = 25000 + 50000 = \mathbf{75,000}$ — a **10× penalty** for wrong parenthesization!

> [!TRAP]
> **Why is $\Theta(nW)$ for 0/1 Knapsack NOT polynomial time?** Because the input size in bits to represent capacity $W$ is $b = \lceil \log_2 W \rceil$, so $W = 2^b$. Thus $\Theta(nW) = \Theta(n \cdot 2^b)$ is **exponential in bit-length** (pseudo-polynomial)!

## Solved Practice Questions & PYQs

### [GATE CS Algorithms | MCQ]
What is the length of the **Longest Common Subsequence (LCS)** of strings $X = \text{"AGGTAB"}$ and $Y = \text{"GXTXAYB"}$?
**Correct Answer:** B
**Solution:** Tracing matching characters in order produces $\text{"GTAB"}$ of length **4** ($G$ at index 2/1, $T$ at 4/3, $A$ at 5/5, $B$ at 6/7). No common subsequence of length 5 exists.
