SDE & MLE Prep

322. Coin Change

Problem

Return the fewest coins that add up to amount, using unlimited coins of each denomination in coins, or −1 if it can't be done.

Example: coins = [1,2,5], amount = 11 → 3 (5 + 5 + 1); coins = [2], amount = 3 → -1

Constraints: amount ≤ 10⁴.

dp[a] = fewest coins summing to a = 1 + min(dp[a − c]) over coins. (BFS over amounts also works.)

coins [1,2,5], amount 11
a    0 1 2 3 4 5 6 7 8 9 10 11
dp   0 1 1 2 2 1 2 2 3 3 2  3

Complexity: O(amount × coins).

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        INF = amount + 1
        dp = [0] + [INF] * amount
        for a in range(1, amount + 1):
            for c in coins:
                if c <= a:
                    dp[a] = min(dp[a], dp[a - c] + 1)
        return -1 if dp[amount] == INF else dp[amount]