Coin Change
cheatsheet1999 opened this issue · 0 comments
cheatsheet1999 commented
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
A very interesting and typical Dynamic Programming problem, I really am not a big fan of it.
You may find this video helpful
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
// cannot use greedy: 1 3 4 5, if minus 5 first, ends up with 3 steps, but 3 + 4 only uses 2 steps!!
var coinChange = function(coins, amount) {
// dp[i] represents the least amount of coins that can make the value equals to the i
const dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for(let i = 1; i <= amount; i++) {
for(let coin of coins) {
if(i - coin >= 0) {
// dp[i - coin] + 1 because at least we will have 1 step
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
};