@@ -10,9 +10,11 @@ public class CoinChange {
10
10
public static void main (String [] args ) {
11
11
12
12
int amount = 12 ;
13
- int [] coins = {1 , 2 , 5 };
13
+ int [] coins = {2 , 4 , 5 };
14
14
15
15
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
+
16
18
}
17
19
18
20
/**
@@ -29,22 +31,49 @@ public static int change(int[] coins, int amount) {
29
31
30
32
for (int coin : coins ) {
31
33
for (int i =coin ; i <amount +1 ; i ++) {
32
- combinations [i ] += combinations [i -coin ];
34
+ combinations [i ] += combinations [i -coin ];
33
35
}
34
36
// Uncomment the below line to see the state of combinations for each coin
35
37
// printAmount(combinations);
36
38
}
37
39
38
40
return combinations [amount ];
39
41
}
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
+ }
40
71
41
72
// A basic print method which prints all the contents of the array
42
73
public static void printAmount (int [] arr ) {
43
-
44
74
for (int i =0 ; i <arr .length ; i ++) {
45
75
System .out .print (arr [i ] + " " );
46
76
}
47
77
System .out .println ();
48
78
}
49
-
50
- }
79
+ }
0 commit comments