给定一组硬币所需的最小硬币数量,以使所有数字达到给定数量。

时间:2015-10-19 13:25:52

标签: dynamic-programming greedy

Ex. Set of Coins - {1,2,5,10} ;  MaxSum -20
    We have to find a set of coins with minimum coins which can make any   number  up to 20. 
I came up with a greedy approach depending on division of the max sum by largest coin gives remainder 0 or 1.  

20/10 = 2 -- remainder =0 ; In case of zero remainder, reduce the quotient by 1 to get number of 10 coins(2-1=1) and continue with Maxsum =10(same as coin) and set{1,2,5}   
Answer Set={10} (only 1 coin of 10 added - quotient-1)

10/5=2 -- remainder =0 ; Answer Set={10,5} (add only 1(quotient-1) 5-coins) MaxSum=5
Answer Set= {10,5}
set={1,2}

5/2= 2 -- remainder =1; In case of non zero remainder, add coins equal to quotient(add 2 coins of 2 ) and set Maxsum= Subtract one from Coin chosen from set(here it is 2) = 2-1 = 1.
Answer Set = {10,5,2,2} ( coins added =quotient )
Set={1} 
Maxsum=1 (one subtracted from coin chosen from set)

Base Case- Set={1} and MaxSum =1 . So we need only 1 coin of 1.
Answer Set= {10,5,2,2,1}

我在很多案例中尝试过相同的逻辑。它有效,但它是否正确?

0 个答案:

没有答案