Search code examples
javarecursiondynamic-programmingcoin-change

Coin change algorithm always returning one


/**
 * 
 * @param d
 *            currency divisions
 * @param p
 *            target
 * @return number of coins
 */
public static int change(int[] d, int p) {
    int[] tempArray = new int[p*2]; // 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 coints
        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[1 - value];//assign it
                }
            }
        }
        tempArray[i] = min; //assign min value to array of coins
    }
    return tempArray[p];
}

Can anyone help me see why this is not working please? The method is meant to be given an input of values representing coins, it has an infinite number of these coints with which to form the integer p, the method is to return the minimum number of coins used to get to p.


Solution

  • tempArray is initialized to 0 on all indices. using tempArray[1-value] is basically giving you 0. So, all indices from 1 to p has the value 1 + tempArray[1-value] This is 1. Also, tempArray[1-value] is a negetive index. I think you meant tempArray[i-value]