Skip to content

Instantly share code, notes, and snippets.

@furf
Last active June 17, 2021 13:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save furf/5609175 to your computer and use it in GitHub Desktop.
Save furf/5609175 to your computer and use it in GitHub Desktop.
Given a set of coin denominators, find the minimum number of coins to give a certain amount of change.
function makeChange (amount) {
var change = {},
i = 0,
coins = makeChange.COINS,
coin;
while (amount && (coin = coins[i++])) {
if (amount >= coin) {
change[coin] = ~~(amount / coin);
amount %= coin;
}
}
return change;
}
makeChange.COINS = [100, 25, 10, 5, 1];
makeChange(199); // {1: 4, 10: 2, 25: 3, 100: 1}
@LukeMeyer94
Copy link

Fails for some sets of coin denominations

makeChange.coins = [10,8,5,1];
makeChange(16) // { 10: 1, 1: 6 }

as you can see, the result should be { 8: 2 }

@furf
Copy link
Author

furf commented Jul 18, 2019

Good catch. My solution was overly simplistic. I'll need to go back and look at it. Thanks!

@LukeMeyer94
Copy link

@furf no problem! We're using this as an interview question (ours accepts dynamic denominations as well) and I know there's several ways to go about doing this, so i was looking around

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment