아카이브

[PS] Leet | 322. 동전 교환 본문

CS/PS

[PS] Leet | 322. 동전 교환

Rayi 2025. 3. 28. 16:09

문제

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.

예시

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

 

조건

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

DP로 해결합니다.

 

각 잔액 별 최소 필요한 동전 수를 담을 리스트를 만든 뒤,

 

각 동전 종류 coin에 대해 (이전까지 잔액에서 필요했던 최소 동전 수)(잔액에서 coin을 뺀 만큼에서 필요한 최소 동전 수 + 1) 중 더 작은 수를 찾습니다.

/**
 * @param {number[]} coins
 * @param {number} amount
 * @return {number}
 */
var coinChange = function(coins, amount) {
    let coinNums = [0];
    let minNum = 0;
    
    for (let i=1; i<=amount; ++i) {
        coinNums.push(amount + 1);
    }

    for (const coin of coins) {
        for (let i=coin; i<amount+1; ++i) {
            coinNums[i] = Math.min(coinNums[i], coinNums[i-coin] + 1);
        }
    }
    minNum = (coinNums[amount] !== amount + 1)? coinNums[amount] : -1;

    return minNum;
};

amount = n, coin 종류 = m 일 때

시간 복잡도 : O(nm)

공간 복잡도 : O(n)

728x90

'CS > PS' 카테고리의 다른 글

[PS] Leet | 1143. 가장 긴 공통 배열  (0) 2025.04.05
[PS] Leet | 300. 가장 긴 증가 수열  (0) 2025.04.02
[PS] Leet | 11. 가장 큰 컨테이너  (0) 2025.03.24
[PS] 같은 수의 뉴런  (0) 2025.03.21
[PS] Leet | 15. 세 개의 합  (0) 2025.03.21
Comments