我正在尝试编写代码以返回构成给定数字所需的最少硬币数量。我的方法的输入是一组有效硬币,以及我尝试制作的数字。
public static int change(int[] d, int p) {
int[] tempArray = new int[p + 1]; // tempArray to store set
// of coins forming
// answer
for (int i = 1; i <= p; i++) { // cycling up to the wanted value
int min = Integer.MAX_VALUE; // assigning current minimum number of
// coins
for (int value : d) {// cycling through possible values
if (value <= i) {
if (1 + tempArray[i - value] < min) { // if current value is
// less than min
min = 1 + tempArray[i - value];// assign it
}
}
}
tempArray[i] = min; // assign min value to array of coins
}
return tempArray[p];
}
但是,当我填写以下内容时,这适用于大多数情况:
int[] test = {2,3,4};
System.out.println("answer = " + change(test, 6));
答案应该是2吧?但它打印出来:
-2147483647
我错过了什么?