Skip to content

Coin Change #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
cheatsheet1999 opened this issue Sep 6, 2021 · 0 comments
Open

Coin Change #13

cheatsheet1999 opened this issue Sep 6, 2021 · 0 comments

Comments

@cheatsheet1999
Copy link
Owner

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.
Screen Shot 2021-09-05 at 11 57 36 PM

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];
};
@cheatsheet1999 cheatsheet1999 changed the title Largest numbers in a range Coin Change Sep 9, 2021
kyxg added a commit to kyxg/FrontEndCollection that referenced this issue Jan 4, 2022
kyxg added a commit to kyxg/FrontEndCollection that referenced this issue Jan 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant