@@ -10,9 +10,11 @@ public class CoinChange {
1010 public static void main (String [] args ) {
1111
1212 int amount = 12 ;
13- int [] coins = {1 , 2 , 5 };
13+ int [] coins = {2 , 4 , 5 };
1414
1515 System .out .println ("Number of combinations of getting change for " + amount + " is: " + change (coins , amount ));
16+ System .out .println ("Minimum number of coins required for amount :" + amount + " is: " + minimumCoins (coins , amount ));
17+
1618 }
1719
1820 /**
@@ -29,22 +31,49 @@ public static int change(int[] coins, int amount) {
2931
3032 for (int coin : coins ) {
3133 for (int i =coin ; i <amount +1 ; i ++) {
32- combinations [i ] += combinations [i -coin ];
34+ combinations [i ] += combinations [i -coin ];
3335 }
3436 // Uncomment the below line to see the state of combinations for each coin
3537 // printAmount(combinations);
3638 }
3739
3840 return combinations [amount ];
3941 }
42+ /**
43+ * This method finds the minimum number of coins needed for a given amount.
44+ *
45+ * @param coins The list of coins
46+ * @param amount The amount for which we need to find the minimum number of coins.
47+ * Finds the the minimum number of coins that make a given value.
48+ **/
49+ public static int minimumCoins (int [] coins , int amount ) {
50+ //minimumCoins[i] will store the minimum coins needed for amount i
51+ int [] minimumCoins = new int [amount +1 ];
52+
53+ minimumCoins [0 ] = 0 ;
54+
55+ for (int i =1 ;i <=amount ;i ++){
56+ minimumCoins [i ]=Integer .MAX_VALUE ;
57+ }
58+ for (int i =1 ;i <=amount ;i ++){
59+ for (int coin :coins ){
60+ if (coin <=i ){
61+ int sub_res = minimumCoins [i -coin ];
62+ if (sub_res != Integer .MAX_VALUE && sub_res + 1 < minimumCoins [i ])
63+ minimumCoins [i ] = sub_res + 1 ;
64+ }
65+ }
66+ }
67+ // Uncomment the below line to see the state of combinations for each coin
68+ //printAmount(minimumCoins);
69+ return minimumCoins [amount ];
70+ }
4071
4172 // A basic print method which prints all the contents of the array
4273 public static void printAmount (int [] arr ) {
43-
4474 for (int i =0 ; i <arr .length ; i ++) {
4575 System .out .print (arr [i ] + " " );
4676 }
4777 System .out .println ();
4878 }
49-
50- }
79+ }
0 commit comments