I'm having trouble figuring out my last section of code for a Dynamic Coin Changing Problem. I have included the code below.
I can't figure out the last else
. Should I just use the greedy algorithm at that point or can I calculate the answer from values already in the table? I've worked hard on trying to understand this problem and I think I'm pretty close. The method finds the minimum amount of coins needed to make a certain amout of change by creating a table and using the results that are stored in the table to solve the larger problem without using recursion.
public static int minCoins(int[] denom, int targetAmount){
int denomPosition; // Position in denom[] where the first spot
// is the largest coin and includes every coin
// smaller.
int currentAmount; // The Amount of money that needs to be made
// remainingAmount <= initalAmount
int[][] table = new int[denom.length][targetAmount+1];
for(denomPosition = denom.length-1 ; denomPosition >= 0 ; denomPosition--) {
for(currentAmount = 0 ; currentAmount <= targetAmount ; currentAmount++){
if (denomPosition == denom.length-1){
table[denomPosition][currentAmount] =
currentAmount/denom[denomPosition];
}
else if (currentAmount<denom[denomPosition]){
table[denomPosition][currentAmount] =
table[denomPosition+1][currentAmount];
}
else{
table[denomPosition][currentAmount] =
table[denomPosition+1][currentAmount]-
table[denomPosition][denom[denomPosition]]-1;
}
}
}
return table[0][targetAmount];
}
You don't need to switch to a greedy algorithm for solving the coin changing problem, you can solve it with a dynamic programming algorithm. For instance, like this:
This is actually the correct version of this algorithm.
Are you over thinking this? If we were trying to give 68 cents change using U.S. coins…
Would ‘denom’ be { 25, 10, 5, 1 } ?
And wouldn’t the answer be “2 quarters, 1 dime, 1 nickel, and 3 pennies” = ‘2 + 1 + 1 + 3 = 7’? So the function should return the value 7. Right?