[JS] Coin Change

2022. 9. 18. 13:51

🔒 문제 (LeetCode 322)

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.

Constraints:

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 231 - 1
  • 0 <= amount <= 104

 

🌊 입출력

Example 1:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Example 3:

Input: coins = [1], amount = 0
Output: 0

 


 

🔑 해결

🌌 알고리즘 - DP

/**
 * @param {number[]} coins
 * @param {number} amount
 * @return {number}
 */
var coinChange = function(coins, amount) {
    // dp[i] = i가 되는데 필요한 coin의 최소 개수
    const dp = new Array(amount + 1).fill(Infinity)
    dp[0] = 0
    
    for(let i = 0; i <= amount; i++) {
        for(const coin of coins) {
            if(i - coin >= 0) {
                dp[i] = Math.min(dp[i], dp[i-coin] + 1)
            }
        }
    }
    
    return dp[amount] === Infinity ? -1 : dp[amount]
};

'코딩테스트 (JS) > DP' 카테고리의 다른 글

[JS] Integer Break  (0) 2022.09.23
[JS] Longest String Chain  (0) 2022.09.17
[JS] Edit Distance  (0) 2022.09.17
[JS] Delete Operation for Two Strings  (0) 2022.09.14
[JS] Longest Common Subsequence  (0) 2022.09.13

+ Recent posts