09 Dynamic Programming Algorithms
09 Dynamic Programming Algorithms
Credits: Many of these slides were originally authored by Jeff Edmonds, York University. Thanks Jeff!
Optimization Problems
• For most, the best known algorithm runs in exponential time.
• Some have quick Greedy or Dynamic Programming algorithms.
COSC 3101E 2
What is Dynamic Programming?
COSC 3101E 3
What is Dynamic Programming?
COSC 3101E 4
Example 1
COSC 3101E 5
Fibonacci Example
Time?
COSC 3101E 6
Fibonacci Example
Time:
Exponential
Waste time
COSC 3101E 7 redoing work
Memoization
Definition: An algorithmic technique which saves (memoizes) a computed answer
for later reuse, rather than recomputing the answer.
•The idea was further developed by Robin Popplestone in his Pop2 language.
•This same principle is found at the hardware level in computer architectures which
use a cache to store recently accessed memory locations.
•["'Memo' functions: and machine learning", Donald Michie, Nature, 218, 19-22,
1968].
COSC 3101E 8
Memoization in Optimization
COSC 3101E 9
Memoization
COSC 3101E 10
From Memoization to Dynamic Programming
COSC 3101E 11
Dynamic Programming
First determine the complete set of subinstances
{100, 99, 98,…, 0}
1
COSC 3101E 0 12
Dynamic Programming
1
0
COSC 3101E 13
Dynamic Programming
Time Complexity?
Linear!
COSC 3101E 14
Dynamic Programming vs Divide-and-Conquer
COSC 3101E 15
Dynamic Programming vs Divide-and-Conquer
COSC 3101E 16
A Sequence of 3 Steps
COSC 3101E 17
Elements of Dynamic Programming
2. Overlapping subproblems
– The space of subproblems must be small; i.e., the same subproblems
are encountered over and over
COSC 3101E 18
Elements of Dynamic Programming
COSC 3101E 19
Example 2. Making Change
Making Change
COSC 3101E 21
Example
COSC 3101E 22
A simple solution
• Idea: Solve first for one cent, then two cents, then three cents, etc., up
to the desired amount
– Save each answer in an array !
• For each new amount N, compute all the possible pairs of previous
answers which sum to N
– For example, to find the solution for 13¢,
• First, solve for all of 1¢, 2¢, 3¢, ..., 12¢
• Next, choose the best solution among:
– Solution for 1¢ + solution for 12¢
– Solution for 2¢ + solution for 11¢
– Solution for 3¢ + solution for 10¢
– Solution for 4¢ + solution for 9¢
– Solution for 5¢ + solution for 8¢
– Solution for 6¢ + solution for 7¢
COSC 3101E 27
An even better dynamic programming solution
COSC 3101E 28
Making Change: Recurrence Relation
Let mincoins(sum) minimum number of coins required to make change totalling sum.
Let onecoin(sum) one coin in optimal set of coins to make change totalling sum.
Then
mincoins(sum) min(mincoins(sum - d ) 1)
d sum
onecoin(sum) argmin(mincoins(sum - d ))
d sum
COSC 3101E 29
function coins = makechange(d, sum)
%precondition: d=set of denominations (must include penny), sum=change to be made
%postcondition: coins = a minimal set of coins summing to sum
mincoins(0) = 0
mincoins(1…sum) = ∞
for i = 1:sum
%LI: mincoins(0...i-1) holds the min number of coins required to make change of (0…i-1).
% onecoin(1...i-1) holds the value of one coin in a minimal set of coins making the correct change.
for j = 1:length(d) %try each denomination
if d(j) <= i & mincoins(i-d(j)) + 1 < mincoins(i)
mincoins(i) = mincoins(i-d(j)) + 1 %best solution so far
onecoin(i) = d(j)
ncoins = mincoins(sum)
change = sum
for i = 1:ncoins %recover coins in optimal set
coins(i) = onecoin(change)
change = change - coins(i)
COSC 3101E 30
How good is the algorithm?
COSC 3101E 31
Elements of Dynamic Programming
COSC 3101E 32
Elements of Dynamic Programming
COSC 3101E 33
Example Proof of Optimal Substructure
COSC 3101E 34
Optimal Substructure
• Optimal substructure means that
– Every optimal solution to a problem contains...
– ...optimal solutions to subproblems
• Optimal substructure does not mean that
– If you have optimal solutions to all subproblems...
– ...then you can combine any of them to get an optimal solution to a larger
problem.
• Example: In Canadian coinage,
– The optimal solution to 7¢ is 5¢ + 1¢ + 1¢, and
– The optimal solution to 6¢ is 5¢ + 1¢, but
– The optimal solution to 13¢ is not 5¢ + 1¢ + 1¢ + 5¢ + 1¢
• But there is some way of dividing up 13¢ into subsets with optimal
solutions (say, 11¢ + 2¢) that will give an optimal solution for 13¢
– Hence, the making change problem exhibits optimal substructure.
COSC 3101E 35
Optimal Substructure
COSC 3101E 36
Don’t all problems have this optimal
substructure property?
Longest simple path
B
1 2
• Consider the following graph: 3
1 4
A C D
COSC 3101E 38
Example 2. Knapsack Problem
COSC 3101E 39
The (General) 0-1 Knapsack Problem
COSC 3101E 40
What are good greedy local choices?
COSC 3101E 41
Some example problem instances
Suppose vi wi
COSC 3101E 43
Some example problem instances
COSC 3101E 44
Approximate Greedy Solution
ˆ 1
V V , where
2
Vˆ Total value of items selected by greedy algorithm
V Total value of items selected by optimal algorithm
COSC 3101E 45
End of Lecture 19
1
Claim:Vˆ V
2
Proof:
Let W capacity of knapsack.
Let s value (weight) of object in optimal solution but not selected by greedy algorithm.
1
Suppose Vˆ V
2
1
Then s V (since object was not selected by greedy algorithm)
2
But since Vˆ s V W , object would be selected by greedy algorithm.
Contradiction!
And running time O( n log n)
where n number of items
COSC 3101E 48
Dynamic Programming Solution
0 if i 0 or w 0
Then c i ,w c i 1, w if w i w
max v c [i 1, w w ], c [i 1, w ] if i 0 and w w
i i i
COSC 3101E 49
Correctness
Let W capacity of knapsack (kg)
Let (v i ,w i ) value ($) and weight (kg) of item i [1...n]
Let c[i ,w ] value of optimal solution for knapsack of capacity w and items drawn from [1...i ]
0 if i 0 or w 0
Then c i ,w c i 1, w if w i w
max v c [i 1, w w ], c [i 1, w ] if i 0 and w w
i i i
Idea: c[i 1,w ] value of optimal solution for capacity w and items drawn only from [1...i 1]
What happens when we are also allowed to consider item i ?
COSC 3101E 50
Bottom-Up Computation
Let W capacity of knapsack (kg)
Let (v i ,w i ) value ($) and weight (kg) of item i [1...n ]
Let c[i ,w ] value of optimal solution for knapsack of capacity w and items drawn from [1...i ]
0 if i 0 or w 0
Then c i ,w c i 1, w if w i w
max v c [i 1, w w ], c [i 1, w ] if i 0 and w w
i i i
c[i,w] w
i Allowed Items 0 1 2 … w … W
0 {}
1 {1}
2 {1 2}
… …
i {1 2 … i} c[i,w]
… …
n {1 2 … n}
COSC 3101E 51
Integer Knapsack Solution
COSC 3101E 52
Integer Knapsack Solution
Recurrence relation
COSC 3101E 53
Example Capacity W 6
0 if i 0 or w 0
Then c i ,w c i 1, w if w i w
max v c [i 1, w w ], c [i 1, w ] if i 0 and w w
i i i
i v w
1 1 2
c[i,w] w
2 3 3 i Allowed Items 0 1 2 3 4 5 6
3 5 1 0 {} 0 0 0 0 0 0 0
4 2 5
5 6 3 1 {1} 0 0 1 1 1 1 1
6 10 5 2 {1 2} 0 0 1 3 3 4 4
3 {1 2 3} 0 5 5 6 8 8 9
4 {1 2 3 4} 0 5 5 6 8 8 9
5 {1 2 3 4 5} 0 5 5 6 11 11 12
6 {1 2 3 4 5 6} 0 5 5 6 11 11 15
COSC 3101E 54
Solving for the Items to Pack
0 if i 0 or w 0
Then c i ,w c i 1, w if w i w
max v c [i 1, w w ], c [i 1, w ] if i 0 and w w
i i i
i v w c[i,w] w i n
1 1 2 i Allowed Items 0 1 2 3 4 5 6 w W
2 3 3 0 {} 0 0 0 0 0 0 0
3 5 1 1 {1} 0 0 1 1 1 1 1 items {}
4 2 5 2 {1 2} 0 0 1 3 3 4 4 loop for i n downto 1
5 6 3 3 {1 2 3} 0 5 5 6 8 8 9
if c[i ,w ] c[i 1,w ]
6 10 5 4 {1 2 3 4} 0 5 5 6 8 8 9
5 {1 2 3 4 5} 0 5 5 6 11 11 12 items items {i }
6 {1 2 3 4 5 6} 0 5 5 6 11 11 15 w w w i
COSC 3101E 55
Second Example Capacity W 6
0 if i 0 or w 0
Then c i ,w c i 1, w if w i w
max v c [i 1, w w ], c [i 1, w ] if i 0 and w w
i i i
i v w
1 1 2
c[i,w] w
2 4 3 i Allowed Items 0 1 2 3 4 5 6
3 2 1
4 5 4 0 {} 0 0 0 0 0 0 0
5 4 3 1 {1} 0 0 1 1 1 1 1
6 2 3
2 {1 2} 0 0 1 4 4 5 5
3 {1 2 3} 0 2 2 4 6 6 7
4 {1 2 3 4} 0 2 2 4 6 7 7
5 {1 2 3 4 5} 0 2 2 4 6 7 8
6 {1 2 3 4 5 6} 0 2 2 4 6 7 8
COSC 3101E 56
Knapsack Problem: Running Time
COSC 3101E 57
End of Lecture 20
i v w
1 1 2
c[i,w] w
2 4 3 i Allowed Items 0 1 2 3 4 5 6
3 2 1
4 5 4 0 {} 0 0 0 0 0 0 0
5 4 3 1 {1} 0 0 1 1 1 1 1
6 2 3
2 {1 2} 0 0 1 4 4 5 5
3 {1 2 3} 0 2 2 4 6 6 7
4 {1 2 3 4} 0 2 2 4 6 7 7
5 {1 2 3 4 5} 0 2 2 4 6 7 8
6 {1 2 3 4 5 6} 0 2 2 4 6 7 8
COSC 3101E 59
Observation from Last Day (Jonathon):
We could still implement this recurrence relation directly as a recursive
program.
0 if i 0 or w 0
Then c i ,w c i 1, w if w i w
max v c [i 1, w w ], c [i 1, w ] if i 0 and w w
i i i
c[i,w] w
i Allowed Items 0 1 2 3 4 5 6
0 {} 0 0 0 0 0 0 0
1 {1} 0 0 1 1 1 1 1
2 {1 2} 0 0 1 4 4 5 5
3 {1 2 3 } 0 2 2 4 6 6 7
4 {1 2 3 4 } 0 2 2 4 6 7 7
5 {1 2 3 4 5 } 0 2 2 4 6 7 8
6 {1 2 3 4 5 6 } 0 2 2 4 6 7 8
COSC 3101E 60
Recall: Memoization in Optimization
COSC 3101E 61
Memoization
COSC 3101E 62
From Memoization to Dynamic Programming
COSC 3101E 63
Dynamic Programming Examples
1. Fibonacci numbers
2. Making change
3. 0-1 Knapsack problem
4. Activity Scheduling with profits
COSC 3101E 64
Recall: The Activity (Job/Event) Selection Problem
Ingredients:
•Instances: Events with starting and finishing times
<<s1,f1>,<s2,f2>,… ,<sn,fn>>.
•Solutions: A set of events that do not overlap.
•Value of Solution: The number of events scheduled.
•Goal: Given a set of events, schedule as many as
possible.
COSC 3101E 65
From Previous Lecture:
Problem can be solved by greedy algorithm
g 2 10
g1 1 g3 1
COSC 3101E
No! 68
Dynamic Programming Solution
Precomputation: Time?
1. Sort activities according to finishing time: f1 f 2 f n (O(n log n))
2. i {1,..., n}, compute H (i) max{l {1, 2,..., i 1}| f l si } (O(n log n))
i.e. H (i ) is the last event that ends before event i starts.
COSC 3101E 69
Step 1. Define an array of values to compute
COSC 3101E 70
Step 2. Provide a Recurrent Solution
2. i {1,..., n}, compute H (i) max{l {1, 2,..., i 1} | f l si } (O(n log n))
i.e. H (i ) is the last event that ends before event i starts.
function A=actselwithp(g, H, n)
% assumes inputs sorted by finishing time
A(0)=0
for i=1:n
A(i)=max(A(i-1), g(i)+A(H(i)))
end
Running time? O(n)
COSC 3101E 72
Step 4. Compute Optimal Solution
Invoke with: printasp(A,H,n,‘Activities to Schedule:’)
function actstring=printasp(A,H,i,actstring)
if A(i)>A(i-1)
actstring = printasp(A, H, H(i), actstring)
actstring = [actstring, sprintf('%d ', i)]
else
actstring = printasp(A, H, i-1, actstring)
COSC 3101E 73
Example
Activity i 1 2 3 4
Start si 0 2 3 2
Finish fi 3 6 6 10
Profit gi 20 30 20 30
H(i) ? ? ? ?
COSC 3101E 74
Example
Activity i 1 2 3 4
Start si 0 2 3 2
Finish fi 3 6 6 10
Profit gi 20 30 20 30
H(i) 0 ? ? ?
COSC 3101E 75
Example
Activity i 1 2 3 4
Start si 0 2 3 2
Finish fi 3 6 6 10
Profit gi 20 30 20 30
H(i) 0 0 ? ?
COSC 3101E 76
Example
Activity i 1 2 3 4
Start si 0 2 3 2
Finish fi 3 6 6 10
Profit gi 20 30 20 30
H(i) 0 0 1 ?
COSC 3101E 77
Example
Activity i 1 2 3 4 A(0) 0
Start si 0 2 3 2
A(1) max{0, 20 A( H (1))} 20
Finish fi 3 6 6 10
A(2) max{20,30 A( H (2))} 30
Profit gi 20 30 20 30
A(3) max{30, 20 A( H (3))} 40
H(i) 0 0 1 0
COSC 3101E 78
Dynamic Programming Examples
1. Fibonacci numbers
2. Making change
3. 0-1 Knapsack problem
4. Activity scheduling with profits
5. Longest common subsequence
COSC 3101E 79
Longest Common Subsequence
COSC 3101E 80
Example 3. Longest Common Subsequence
COSC 3101E 81
Brute-force Algorithm
Time: (n2m ).
2m subsequences of X to check.
COSC 3101E 82
Step 1. Define Data Structure
• Input: 2 sequences, X = x1, . . . , xm and Y = y1, . . . , yn.
COSC 3101E 83
Step 2. Define Recurrence
Case 1. Input sequence is empty
COSC 3101E 84
Recurrence
Case 2.
Last elements match:
must be part of an
LCS
X
Xi 1
Yj 1
Y
Z __ __ … __ __
m
COSC 3101E 85
Recurrence
X
Xi 1
Case 3. Last elements don’t match: at
most one of them is part of LCS
Yj
Y
X Choose!
Xi X
Xi
Yj
Y Yj 1
Y
COSC 3101E 86
Step 3. Provide an Algorithm
COSC 3101E 90
Step 4. Compute Optimal Solution
COSC 3101E 91
Example
COSC 3101E 92