07 DP Coin Change Problem
07 DP Coin Change Problem
Dynamic Programming
Greedy solution is
optimal for any amount and “normal’’ set of denominations
The greedy method would not work if we did not have 5¢ coins
For 31 cents, the greedy method gives seven coins (25+1+1+1+1+1+1),
but we can do it with four (10+10+10+1)
The greedy method also would not work if we had a 21¢ coin
For 63 cents, the greedy method gives six coins (25+25+10+1+1+1), but
we can do it with three (21+21+21)
Value 1 2 3 4 5 6 7 8 9 10
Min # of coins 1 1 1
Value 1 2 3 4 5 6 7 8 9 10
Min # of coins 1 2 1 2 1 2 2 2
Value 1 2 3 4 5 6 7 8 9 10
Min # of coins 1 2 1 2 1 2 3 2 3 2
minNumCoins(M-1) + 1
min minNumCoins(M-3) + 1
minNumCoins(M) =
of
minNumCoins(M-5) + 1
minNumCoins(M-c1) + 1
min minNumCoins(M-c2) + 1
minNumCoins(M) =
of …
minNumCoins(M-cd) + 1
1. RecursiveChange(M, c, d)
2. if M = 0
3. return 0
4. bestNumCoins infinity
5. for i 1 to d
6. if M ≥ ci
7. numCoins RecursiveChange(M – ci , c, d)
8. if numCoins + 1 < bestNumCoins
9. bestNumCoins numCoins + 1
10. return bestNumCoins
77
76 74 70
75 73 69 73 71 67 69 67 63
... ..
70 70 70 70 70
.
Dr. Md. Abul Kashem Mia, Professor, CSE Dept, BUET
We Can Do Better
1. DPChange(M, c, d)
2. bestNumCoins0 0 Running time: O(M*d)
3. for m 1 to M
4. bestNumCoinsm infinity
5. for i 1 to d
6. if m ≥ ci
7. if bestNumCoinsm – c + 1 < bestNumCoinsm
i
8. bestNumCoinsm bestNumCoinsm – c + 1
i
9. return bestNumCoinsM
0 0 1 2 1 2 3 2
0 0 1 2 3 4 5 6
0 1
0 1 0 1 2 1 2 3 2 1
0 1 2 3 4 5 6 7
0 1 2
0 1 2
0 1 2 1 2 3 2 1 2
0 1 2 1 0 1 2 3 4 5 6 7 8
0 1 2 3
0 1 2 1 2 3 2 1 2 3
0 1 2 1 2 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4
0 1 2 1 2 3
c = (1, 3, 7)
0 1 2 3 4 5 M=9
…
… + bn
... [1-0.5^i<1]