Minimum Coin Problem
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem Description
There are n coins of different denominations, and the denominations of each coin are stored in the array T[1:n]. Now use these denomination coins to find money. The number of coins of various denominations that can be used is stored in the array Coins[1:n].
For any amount of money 0≤m≤20001, design a method to find money m with the fewest coins.
For a given 1≤n≤10, the coin denomination array T and the number of coins array Coins of various denominations that can be used, and the money m, 0≤m≤20001, calculate the minimum number of coins to find money m.
There is only 1 integer in the first line of Input
input data to give the value of n, and there are 2 numbers in each line from the second line, namely T[j] and Coins[j]. The last line is the amount of money m to be found.
The Output
output data has only one integer, which represents the minimum number of coins calculated. Output -1 if there is no solution to the problem.
Sample Input
3
1 3
2 3
5 3
18
Sample Output
5
Hint
Source
import java.util.*;
class Main {
static int min(int a, int b) {
return a < b ? a : b;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner ss = new Scanner(System.in);
int n;
final int mm = 20001;
final int coinnum = 15;
int dp[];
int coin[];
int coinn[];
n = ss.nextInt();
dp = new int[mm + 1];
coin = new int[coinnum];
coinn = new int[coinnum];
for (int i = 1; i <= mm; i++) {
dp[i] = mm;
}
for (int i = 0; i < n; i++) {
coin[i] = ss.nextInt();
coinn[i] = ss.nextInt();
}
int m;
m = ss.nextInt();
int i, j, k;
for (i = 0; i < n; i++) {
for (j = 0; j < coinn[i]; j++) {
for (k = m; k >= coin[i]; k--) {
dp[k] = min(dp[k - coin[i]] + 1, dp[k]);
}
}
}
if (dp[m] == mm)
System.out.println(-1);
else
System.out.println(dp[m]);
ss.close();
}
}