5 Dynamic Programming

Design and Analysis of Algorithms · Unit 5 · 8 hrs

Dynamic Programming

Exam-focused notes for Dynamic Programming (Design and Analysis of Algorithms, CSC325): what the TU syllabus asks and how it has actually been tested, with 10 solved past questions from this unit.

Dynamic Programming in short

Dynamic programming (DP) solves a problem by breaking it into overlapping sub-problems, solving each sub-problem exactly once, and storing the result in a table so it never has to be recomputed. This unit contrasts DP with greedy and plain recursion, then applies it to five classic optimization problems, before closing with memoization, the top-down way of getting the same result.

Dynamic Programming: notes

Greedy Algorithms vs Dynamic Programming, Recursion vs Dynamic Programming, Elements of DP Strategy

Dynamic programming applies when a problem has optimal substructure (an optimal solution is built from optimal solutions to its sub-problems, exactly as in greedy) and, unlike greedy, overlapping sub-problems: a naive recursive solution would solve the same sub-problem many times over. Greedy commits to one choice at each step and never reconsiders it, so it is fast but only correct when the greedy-choice property holds; DP instead considers every relevant choice at each step and keeps whichever leads to the best final result, so it always finds the optimum but at a higher memory cost for its table. The fractional knapsack (greedy, exact) versus the 0/1 knapsack (DP, exact, but no greedy rule is provably correct since items cannot be split) is the standard pair illustrating this difference.

Plain (top-down) recursion and dynamic programming solve the same recurrence, but recursion re-derives every sub-problem it revisits, while DP is normally organized bottom-up: sub-problems are solved in order of increasing size and stored in a table, so a larger sub-problem simply looks up the smaller ones it needs instead of recomputing them. Naive recursive Fibonacci, which calls itself twice per level and so repeats the same smaller sub-problems exponentially many times, against an iterative table-filling Fibonacci that computes each value once, is the standard illustration.

Three elements characterize a DP algorithm: substructure, decomposing the problem so the original solution can be expressed in terms of solutions to smaller instances; a table, in which every sub-problem's solution is stored exactly once after being computed; and bottom-up computation, filling the table from the smallest sub-problems upward so that each entry only depends on entries already filled.

What this unit covers

  • Greedy Algorithms vs Dynamic Programming, Recursion vs Dynamic Programming, Elements of DP Strategy
  • DP Algorithms: Matrix Chain Multiplication, String Editing, Zero-One Knapsack Problem, Floyd Warshwall Algorithm, Travelling Salesman Problem and their Analysis
  • Memoization Strategy, Dynamic Programming vs Memoization

DP Algorithms

2082 · 10 marks

Distinguish between dynamic programming and memorization. Parenthesize the matrices A(30 × 1), B(1 × 40), C(40 × 10) and A(10 × 15), for computing matrix multiplication using dynamic programming.[10]

Show solved answer

Dynamic Programming vs Memoization & Matrix Chain Multiplication

Part 1: Dynamic Programming vs Memoization

FeatureDynamic ProgrammingMemoization
ApproachBottom-upTop-down
ImplementationIterative (fills a table)Recursive with a cache
Sub-problems solvedAll sub-problems computedOnly the sub-problems actually needed
OverheadNo recursion overheadRecursion call/return overhead
StorageResults stored in a table filled in orderResults stored in a lookup table on first computation
NatureA general problem-solving technique (optimal substructure + overlapping subproblems)An optimization applied to recursion by caching results

Key idea: Memoization is essentially the top-down (recursive) way of realizing dynamic programming; it "remembers" previously computed results so they are not recomputed.

Part 2: Matrix Chain Parenthesization

Given data

  • $A = 30 \times 1$
  • $B = 1 \times 40$
  • $C = 40 \times 10$
  • $D = 10 \times 15$ (the last matrix, written A(10 × 15) in the question)

Dimension array: $$p = [30,,1,,40,,10,,15]$$ $p_0=30,\ p_1=1,\ p_2=40,\ p_3=10,\ p_4=15,\quad n=4$

Recurrence

$$m[i][j]=\min_{i\le k<j}{m[i][k]+m[k+1][j]+p_{i-1},p_k,p_j}$$ Base case $m[i][i]=0$.

Length $l=2$

$m[1][2]=0+0+30\cdot1\cdot40=1200,\ s=1$

$m[2][3]=0+0+1\cdot40\cdot10=400,\ s=2$

$m[3][4]=0+0+40\cdot10\cdot15=6000,\ s=3$

Length $l=3$

$m[1][3]$:

  • $k=1:\ 0+400+30\cdot1\cdot10=400+300=700$
  • $k=2:\ 1200+0+30\cdot40\cdot10=1200+12000=13200$

$m[1][3]=700,\ s=1$

$m[2][4]$:

  • $k=2:\ 0+6000+1\cdot40\cdot15=6000+600=6600$
  • $k=3:\ 400+0+1\cdot10\cdot15=400+150=550$

$m[2][4]=550,\ s=3$

Length $l=4$

$m[1][4]$:

  • $k=1:\ m[1][1]+m[2][4]+p_0p_1p_4=0+550+30\cdot1\cdot15=550+450=1000$
  • $k=2:\ m[1][2]+m[3][4]+p_0p_2p_4=1200+6000+30\cdot40\cdot15=7200+18000=25200$
  • $k=3:\ m[1][3]+m[4][4]+p_0p_3p_4=700+0+30\cdot10\cdot15=700+4500=5200$

$$m[1][4]=\min(1000,25200,5200)=1000,\quad s[1][4]=1$$

Optimal parenthesization (from s-table)

  • $s[1][4]=1 \Rightarrow (A_1)(A_2A_3A_4)$
  • $s[2][4]=3 \Rightarrow (A_2A_3)(A_4)$
  • $s[2][3]=2 \Rightarrow (A_2)(A_3)$

Putting it together: $$\big(A,((B,C),D)\big)$$

Result

  • Minimum number of scalar multiplications = $1000$
  • Optimal order: $(A,((B,C),D))$

Verification of the count:

  • $B\cdot C:\ 1\cdot40\cdot10=400$, result $1\times10$
  • $(BC)\cdot D:\ 1\cdot10\cdot15=150$, result $1\times15$
  • $A\cdot(BCD):\ 30\cdot1\cdot15=450$, result $30\times15$
  • Total $=400+150+450=1000$ ✓
Open this answer on its own page →

2082 · 5 marks

How does 0/1 Knapsack problem differ from fractional one? Find the minimum vertex cover in the following graph. [5+0]

  • Mark distribution: [5 + 0] - Part 1 (difference between 0/1 and fractional knapsack): 5 marks - Part 2 (minimum vertex cover of "the following graph"): 0 marks - Missing data: The graph referenced in Part 2 ("the following graph") is NOT included in the question text. No vertex set, no edge lis...
Open this answer on its own page →

2081 · 10 marks

Differentiate between Dynamic Programming and Memoization. Compute the Shortest Path Between Every Pair in the Following Graphs Using Floyd Warshall Algorithm. [10]

Aspect Dynamic Programming Memoization --------- Approach Bottom-up Top-down Implementation Iterative (loops) Recursive with caching Order of solving Solves smaller subproblems first, builds up Breaks main problem down recursively Table filling Fills entire table regardless of need Fills entries ...

Open this answer on its own page →

2081 · 5 marks

Define order statistics problem. Find the edit distance between 'cat' and 'car' using dynamic programming. [5]

Show solved answer

Order Statistics Problem and Edit Distance


Part 1: Order Statistics Problem

Definition:

Given a set (or array) $A$ of $n$ elements drawn from a totally ordered set, the $i$-th order statistic is the $i$-th smallest element of $A$.

  • Input: An array $A$ of $n$ elements and an integer $i$ where $1 \le i \le n$.
  • Output: The element $e \in A$ that is greater than exactly $i-1$ other elements of $A$.

Special cases:

  • $i = 1$ → minimum element
  • $i = n$ → maximum element
  • $i = \lfloor (n+1)/2 \rfloor$ → median

The selection problem is the general problem of finding the $i$-th order statistic, solvable in expected linear time $O(n)$ (randomized-select) or worst-case $O(n)$ (median-of-medians).


Part 2: Edit Distance between 'cat' and 'car'

Given Data

  • $X = \text{"cat"}$, length $m = 3$
  • $Y = \text{"car"}$, length $n = 3$
  • Operation costs: insert = delete = replace = $1$

Recurrence

$$ dp[i][j] = \begin{cases} j & i = 0 \ i & j = 0 \ dp[i-1][j-1] & X[i] = Y[j] \ 1 + \min\big(dp[i-1][j],, dp[i][j-1],, dp[i-1][j-1]\big) & X[i] \neq Y[j] \end{cases} $$

Filling the Table

Initialization: first row = $0,1,2,3$; first column = $0,1,2,3$.

Row i=1 (X='c'):

  • $dp[1][1]$: c=c → $dp[0][0]=0$
  • $dp[1][2]$: c≠a → $1+\min(2,0,1)=1$
  • $dp[1][3]$: c≠r → $1+\min(3,1,2)=2$

Row i=2 (X='a'):

  • $dp[2][1]$: a≠c → $1+\min(0,2,1)=1$
  • $dp[2][2]$: a=a → $dp[1][1]=0$
  • $dp[2][3]$: a≠r → $1+\min(2,0,1)=1$

Row i=3 (X='t'):

  • $dp[3][1]$: t≠c → $1+\min(1,3,2)=2$
  • $dp[3][2]$: t≠a → $1+\min(0,2,1)=1$
  • $dp[3][3]$: t≠r → $1+\min(1,1,0)=1$

Final DP Table

car
0123
c1012
a2101
t3211

Result

$$\boxed{\text{Edit Distance} = dp[3][3] = 1}$$

Interpretation: Only one replace operation is required - substitute 't' with 'r' to turn "cat" into "car".

Open this answer on its own page →

2079

Matrix Chain Multiplication

Matrix Index Size --------------------- A 1 $5 \times 10$ B 2 $10 \times 15$ C 3 $15 \times 20$ D 4 $20 \times 30$ Number of matrices: $n = 4$ Dimension array: $$p = [p0, p1, p2, p3, p4] = [5, 10, 15, 20, 30]$$ (Note: the question text repeats "ABCD" three times, but only 4 distinct matrices with...

Open this answer on its own page →

2079 · 5 marks

Find the edit distance between the string "ARTIFICIAL" and "NATURAL" Using dynamic programming. [5]

  • String A = "ARTIFICIAL", length $m = 10$: A-R-T-I-F-I-C-I-A-L - String B = "NATURAL", length $n = 7$: N-A-T-U-R-A-L - Operations allowed: insertion, deletion, substitution (each cost 1). $$dp[i][j] = \begin{cases} i & j = 0 \ j & i = 0 \ dp[i-1][j-1] & A[i]=B[j] \ 1 + \min(dp[i-1][j],, dp[i...
Open this answer on its own page →

Greedy Algorithms vs Dynamic Programming, Recursion vs Dynamic Programming, Elements of DP Strategy

2080 · 10 marks

Write down the advantages of dynamic programming over greedy strategy. Find optimal bracketing to multiply 4 matrices of order $2, 3, 4, 2, 5$. [10]

Aspect Dynamic Programming Greedy Strategy --------------------------------------------- Global optimality Guarantees a globally optimal solution by examining all relevant subproblem combinations May settle for a locally optimal choice that is not globally optimal Subproblem reuse Solves each ove...

Open this answer on its own page →

2078 · 10 marks

Explain in brief about the Dynamic Programming Approach for algorithm design. How it differs with recursion? Explain the algorithm for solving the 0/1 Knapsack problem using the dynamic programming approach and explain its complexity.[10]

Dynamic Programming is a method for solving complex problems by breaking them down into simpler overlapping subproblems, solving each subproblem only once, and storing the results (in a table/array) to avoid redundant computation. DP is applicable when a problem has: - Optimal Substructure: Optim...

Open this answer on its own page →

2076 · 5 marks

What do you mean by Dynamic programming strategy? Explain the element of DP. [5]

Dynamic Programming (DP) is an algorithm design strategy used to solve optimization problems by breaking them down into smaller overlapping subproblems, solving each subproblem only once, and storing the results to avoid redundant computation. It finds the optimal solution to a problem by finding...

Open this answer on its own page →

Memoization Strategy, Dynamic Programming vs Memoization

2078 · 5 marks

What do you mean by memorization strategy? Compare memorization with dynamic programming. [5]

Memoization is a technique used to "remember" (store) the result of a computation so that the next time the same sub-problem is encountered, the stored result is reused directly instead of recomputing it, thereby saving time. With memoization, the algorithm is implemented recursively (top-down). ...

Open this answer on its own page →