Dynamic Programming DSA
Dynamic Programming DSA
Practice problems:
DP Pseudocode (Memoization/Top-down):
Create array F[0…n] = NIL Time complexity: O(n)
F[0]=0, F[1] = 1
Space complexity: O(n)
Function Fib(n):
1. if n==0 or n==1 then
2. return n
3. end if
5. F[n-1] = Fib(n-1)
6. end if
8. F[n-2] = Fib(n-2)
9. end if
DP Pseudocode (Tabulation/Bottom-up):
Function Fib(n): Time complexity: O(n)
1. Create array F[0…n]
2. F[0]=0, F[1] = 1 Space complexity: O(n)
3. for i = 2 to n do
4. F[i] = F[i-1]+F[i-2]
5. end for
6. return F[n]
DP Pseudocode (Problem-specific optimization):
Function Fib(n): Time complexity: O(n)
1. f0=0, f1=1
2. for i = 2 to n do Space complexity: O(1)
3. f2 = f0+f1
4. f0 = f1
5. f1 = f2
6. end for
7. return f1
PROBLEM 02. Coin change problem
Consider the problem of making change for M cents using the fewest number of coins. There are d
types of coins C = {c1, c2, …, cd}, each coin’s value is an integer and there are an infinite number of
coins for each coin type. Write a greedy algorithm to make change consisting of coins in C.
1. if M = 0 then
2. return 0
3. end if
5. for i = 1 to d do
7. nc = Recursive-Change(M-C[i], C, d)
9. mnc = nc+1
10. end if
11. end if
Write a program that takes the weights and values of n items, and the capacity W of the knapsack
from the user and then finds the items which would maximize the profit using a dynamic
programming algorithm.
4
item 1: 4.0 kg 20.0 taka
4 20
item 4: 1.0 kg 7.0 taka
3 9
profit: 27 taka
2 12
1 7
5
Example:
Given two strings x and y, find the longest common subsequence and its length.
Example:
x = “ABCBDAB”
y = “BDCABA”
x = “ABBACQ”
y = “XAYZMBNNALQCTRQ”