12-twoup - Making Change Input A set of coin denominations...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
Making Change Input: A set of coin denominations d 1 < d 2 < ··· < d k and a target value n . Output: A minimum-sized collection of coins whose total value is exactly n ; i.e., a 1 ,...,a k N such that k s i =1 a k d k = n and k s i =1 a i is minimized. We will assume d 1 = 1 . 1 A Greedy Strategy Always take the largest coin that doesn’t cause the total to exceed the target value. Suppose d 1 = 1 ,d 2 = 10 3 = 25 , and n = 30 . Greedy solution: a 3 = 1 ,a 2 = 0 1 = 5 . Number of coins: 6 . Optimal solution: a 3 = 0 2 = 3 1 = 0 . Number of coins: 3 . 2
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
A Top-Down Solution If k = 1 , then a 1 = n is the only solution. If k > 1 and d k > n , then we can safely remove d k from the set of denominations. If k > 1 and d k n , we have two cases: If the optimal solution has a k = 0 , then it is the same as if d k were not in the set of denominations. Otherwise, the optimal solution can be obtained from an optimal solution for n d k by adding d k coin. 3 The Minimum Number of Coins Let C ( n,k ) give the minimum number of coins needed to produce a value of n from denominations d 1 ,...,d k . Then C ( ) is n if k = 1 ; C ( 1) if k > 1 and d k > n ; or min( C ( 1) ,C ( n d k ,k ) + 1) if k > 1 and n d k . This recurrence gives a recursive algorithm for computing C ( ) . The running time is exponential in k in the worst case. 4
Background image of page 2
Dynamic Programming The total number of C ( i,j ) s with 0 i n and 1 j k is k ( n + 1) . If we compute the recurrence bottom-up and save all of the computed values in an array, then each value can be computed in constant time. We can therefore compute C ( n,k ) in Θ( nk ) time. Given all of the C ( ) s, we can then Fnd the optimal collection of coins in a greedy fashion. 5 Change ( d [1 ..k ] ,n ) C new Array [0 ..n, 1 ..k ] A new Array [1 ..k ] for i 0 to n C [ i, 1] i for i 0 to n for j 2 to k if i < d [ j ] C [ ] C [ 1] else C [ ] Min ( C [ 1] ,C [ i d [ j ] ,j ] + 1) 6
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
for j 1 to k A [ j ] 0 i n ; j k // Invariant: k l =1 A [ l ] d [ l ] = n i and there is an // optimal solution that includes all of the coins in // A [1 ..k ] , but no additional coins from d [ j + 1 ..k ] .
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 13

12-twoup - Making Change Input A set of coin denominations...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online