Skip to content

Instantly share code, notes, and snippets.

@Muzietto
Created December 31, 2016 18:01
Show Gist options
  • Save Muzietto/a67e7a4f8fc6065c65c63991db0aea1f to your computer and use it in GitHub Desktop.
Save Muzietto/a67e7a4f8fc6065c65c63991db0aea1f to your computer and use it in GitHub Desktop.
Dynamic programming self-tuition - minimal number of coins needed to reach a given total amount (BETTER SOLUTION)
function betterMinNumOfCoins(coinages, amount) {
// sort coinages
coinages = coinages.sort((a,b)=>a-b);
var minCoinage = Math.min.apply(null, coinages);
var dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (var i = 1; i <= amount; i++) {
for (var j = 0; j < coinages.length; j++) {
var coinage = coinages[j];
if (coinage > i) break;
if (dp[i - coinage] + 1 < dp[i]) {
if (dp[i] === Infinity) dp[i] = 0;
dp[i] = dp[i - coinage] + 1;
}
}
}
return dp[amount - 1];
}
@Muzietto
Copy link
Author

Muzietto commented Dec 31, 2016

This one comes from https://www.topcoder.com/community/data-science/data-science-tutorials/dynamic-programming-from-novice-to-advanced/ and it is a lot more conscious and coherent.
It is based on a state matrix dp and it bears most probably more learning potential.

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