-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathDP_MinNumOfCoinChange.java
43 lines (35 loc) · 1.8 KB
/
DP_MinNumOfCoinChange.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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class DP_MinNumOfCoinChange {
private static int minNumOfCoinChange(int[] coins, int amount) {
int max = amount + 1; /* We use this to fill the dp table with default values */
int[] dp = new int[amount + 1]; /* This table will store the answer to our sub problems */
Arrays.fill(dp, max); /* Initialize the dp table */
dp[0] = 0;
for(int i = 1; i < dp.length; i++) { /* Solve every sub-problem from 1 to amount */
for (int coin : coins) { /* For each coin we are given */
if (i >= coin) { /* If it is less than or equal to the sub problem amount */
dp[i] = Math.min(dp[i], dp[i - coin] + 1); /* Try it. See if it gives us a more optimal solution */
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while(t-- > 0) {
String[] details = br.readLine().trim().split("\\s+");
int amount = Integer.parseInt(details[0]);
int numOfCoins = Integer.parseInt(details[1]);
String[] input = br.readLine().trim().split("\\s+");
int[] coins = new int[numOfCoins];
for(int i = 0; i < input.length; i++) {
coins[i] = Integer.parseInt(input[i]);
}
System.out.println(minNumOfCoinChange(coins, amount));
}
}
}