Skip to content

Instantly share code, notes, and snippets.

@Muzietto
Last active December 31, 2016 18:03
Show Gist options
  • Save Muzietto/6f773768a6d6a45518983368be17881f to your computer and use it in GitHub Desktop.
Save Muzietto/6f773768a6d6a45518983368be17881f to your computer and use it in GitHub Desktop.
Dynamic programming self-tuition - minimal number of coins needed to reach a given total amount
function minNumOfCoins(coinages, amount) {
if (amount === 0) return 0;
if (coinages.length === 0 && amount > 0) return Infinity;
var maxCoinage = Math.max.apply(null, coinages);
var otherCoinages = coinages.filter(coinage => coinage !== maxCoinage)
if (amount < maxCoinage) return minNumOfCoins(otherCoinages, amount);
var coinsWithMaxCoinage = minNumOfCoins(coinages, amount - maxCoinage) + 1;
var coinsWithoutMaxCoinage = minNumOfCoins(otherCoinages, amount);
return Math.min(coinsWithMaxCoinage, coinsWithoutMaxCoinage);
}
@Muzietto
Copy link
Author

Muzietto commented Dec 31, 2016

This one comes from https://codility.com/media/train/15-DynamicProgramming.pdf, and it is kinda uit de lucht gegrepen...
Recursion instead of state matrix.

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