Lec 7&8 - Dynamic Programming
Lec 7&8 - Dynamic Programming
Analysis
LECTURE 7 : DYNAMIC PROGRAMMING
Contents
▪ Fibonacci Numbers problem
▪ Dynamic programming Definition
▪ Rod-cutting problem
▪ Top-down approach (Memoization)
▪ Bottom-up approach
▪ Dynamic programming steps
▪ Elements of Dynamic Programming
▪ Matrix Chain Multiplication Problem
▪Longest Common Subsequence problem
Fib(4) Fib(3)
+ +
Fib(1) Fib(0)
Dynamic programming
▪ Dynamic programming is typically applied to optimization problems. In
such problem there can be many solutions. Each solution has a value, and we
wish to find a solution with the optimal value.
▪ Like the divide-and-conquer method, it solves problems by combining the
solutions to subproblems.
▪ Unlike divide and conquer, sub-problems are not independent. Sub-problems
may share sub-sub-problems.
Where pn id the price with no cut at all, r1 + rn-1 is a cut so that we have rods of length 1
and n-1.
Where pi is the price of rod of length i, rn-1 is the revenue from rod of length n-1.
Recursive approach
For n=4:
r4 = max (p1 + r3 ,
p2 + r2 ,
p3 + r1 ,
p4 + r0)
p1 + r4 = 1 + 10 = 11
p2 + r3 = 5 + 8 = 13
r5 = max p3 + r2 = 8 + 5 = 13
p4 + r1 = 9 + 1 = 10
p5 = 10
ALGORITHM DESIGN AND ANALYSIS 16
Elements of Dynamic Programming
When should we look for a dynamic programming solution to a problem?
In other words: The number of unique subproblems < The number of the total subproblems.
Number of Multiplications = 4 * 6 * 3 = 72
Parenthesize the product to get the order in which matrices are multiplied.
The order in which we multiply the matrices has a significant impact on the cost of
evaluating the product.
10 X 5
((A1 A2) A3) = 10 x 5 x 50 = 2,500 multiplications
Total: 7,500 scalar multiplications
Solution 2 : (A1 (A2 A3)): A2 A3 = 100 x 5 x 50 = 25,000
100 X 50
(A1 (A2 A3)) = 10 x 100 x 50 = 50,000
Total: 75,000 scalar multiplications
ALGORITHM DESIGN AND ANALYSIS 20
Matrix Chain Parenthesization Problem
▪ We write: Aij for the product Ai × Ai+1 × · · · × Aj
▪ There is a final matrix multiplication: A1k × A(k+1)n , for some 1 ≤ k ≤ n − 1.
▪ we obtain the recurrence:
pi-1pkpj
Ai…j = Ai…k Ak+1…j for i k < j
m[i, k] m[k+1,j]
2 X 3 3 X 4
➢ Since we do not know the value of k, we will try for i ≤ k < j and the
minimum value of m is the solution.
Example:
i j
,k=1
,k=2
,k=3
k=1
126
126 k=2
k=2
126 k=3
126 = 210
k = 1:
k = 2:
126
k = 3: 126 + 0 + 3 . 2 . 9 = 180
180
But, B, C, B, A and B, D, A, B are longest common subsequences of X and Y (length = 4)
c[i, j] = c[i - 1, j - 1] + 1
▪ Xm-1 and Y
➢Both the above subproblems has the subproblem of finding the LCS of Xm-1 and Yn-1
Case 1: xi = yj