Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

coin-change with a twist

I am trying to solve a classic dynamic programming coin-change problem with a twist. This is a homework question, I am not looking for full solutions, just for a few pointers to see what I am doing wrong.

Input:

  • amount x we want to pay in coins for some value.
  • set d representing number of available coins of denominations (1c, 5c, 10c, 25c, 100c, 200c)

Output:

  • Minimum number of coins that need to exchange hands for the payment.

Assumptions:

  • Cash register operator has unlimited supply of coins and knows how to give optimal change.

What I tried to do so far:

I am trying to build an array C, such that every element C[i], is the /minimum/ number of coins that exchange hands for the amount i.

C[0] = 0

For C[i], I calculate it either by taking minimum of all C[i-di] plus 1, for all available denominations of coins. I then remove the coin I picked from the available coins.

This approach seems to work in simple cases, but when I have, for example:

99 99 0 0 0 1 0

My approach fails, because it's "cheaper" to way $1 which will yield an exchange of 2 coins, than to pay exact 99 cents in cents (exchange of 99 coins).

Any pointers will be appreciated.

like image 287
user1500043 Avatar asked Jul 03 '12 21:07

user1500043


1 Answers

It seems like the problem is that you stop when you get to the value you are looking for. If you keep going, figuring out the minimum number of coins to make values larger than x, then add to that the minimum number of coins for the register operator to make proper change, and take the minimum from this larger list, you should be able to answer this.

Edit: You could simplify this slightly if you used two arrays, one for the values you can make and one for the values the register can make. And then you could compare those in some way to get to your answer.

like image 83
Justin Avatar answered Oct 19 '22 21:10

Justin