Last active
December 31, 2016 18:03
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.