我正在尝试编写代码来返回组成给定数字所需的最少硬币数量。我的方法的输入是一组有效的硬币,以及我尝试制造的数字。
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
我错过了什么?
最佳答案
因为,在第一次迭代期间 tempArray[i] = min;
tempArray[i] 被分配给 MAX,并且在后续迭代[s]期间,min = 1 + tempArray[i - value];
会尝试将 MAX 加一,这基本上会移动位并形成负对应项。
关于java - 代码有时会返回 Integer.MAX_VALUE。无法弄清楚原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7971152/