/
GFG.java
61 lines (52 loc) · 1.53 KB
/
GFG.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* @author Loris Reiff
*
* Number of Coins
* http://www.practice.geeksforgeeks.org/problem-page.php?pid=364
*/
import java.util.Scanner;
class GFG {
/**
* Returns the least amount of coins that are needed to sum up to a value.
* If it is not possible to sum up to the value -1 is returned
*
* @param value The value the coins should sum up to
* @param coins Am array with the values of the different coins available
* @return The least amount of coins needed
*/
public static int minNumberOfCoins(int value, int[] coins) {
int[] table = new int[value + 1];
return minNumberOfCoins(value, coins, table);
}
private static int minNumberOfCoins(int value, int[] coins, int[] table) {
if(value == 0) return 0;
if(value < 0) return -1;
if(table[value] != 0) return table[value];
int min = Integer.MAX_VALUE;
for(int i = 0; i < coins.length; i++) {
int n = minNumberOfCoins(value - coins[i], coins, table);
if(0 <= n && n < min) {
min = n + 1;
}
}
if(min != Integer.MAX_VALUE)
table[value] = min;
else
table[value] = -1;
return table[value];
}
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
int runs = console.nextInt();
for(int i = 0; i < runs; i++) {
int value = console.nextInt();
int numberOfCoins = console.nextInt();
int coins[] = new int[numberOfCoins];
for(int j = 0; j < numberOfCoins; j++) {
coins[j] = console.nextInt();
}
System.out.println(minNumberOfCoins(value, coins));
}
console.close();
}
}