Coin Change

Medium

Topics
ArrayDynamic Programming

Given an array coins (passed as nums) and an integer amount (passed as target), return the fewest coins needed to make up that amount, or -1 if impossible. You have unlimited coins of each type.

Example 1

coins125
answer1 + 5 + 5 = 11
Each coin may be used any number of times, and the answer is how many coins the smallest handful needs — not which coins, and not how many different handfuls exist. Here that is 3. Note that taking the largest coin that fits does not always end up smallest: with coins [1,3,4] and amount 6, that route takes three coins where two suffice.
Chips are the denominations available; below them one smallest handful.
Input:  coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1.

Example 2

coins2
answerno combination reaches 3
No combination reaches 3 at all, which answers -1.
Input:  coins = [2], amount = 3
Output: -1

Constraints

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

To make an amount with the fewest coins, imagine the last coin you place. If it has value c, the rest of the amount is a - c, which is a smaller version of the same problem.

So dp[a] = 1 + min(dp[a - c]) over all coins c. We build these answers from small amounts upward. Because coins can repeat, this is the unbounded knapsack.

Approach

  1. Let dp[a] = fewest coins to make amount a; set dp[0] = 0 and the rest to "infinity".
  2. For each amount 1..amount, try every coin that fits and take dp[a] = min(dp[a], dp[a-c] + 1).
  3. If dp[amount] stayed at infinity, it is unreachable → return -1.

Walkthrough

coins = [1, 2, 5], amount = 11
dp[5]=1, dp[10]=2, dp[11]=min(dp[10]+1, dp[9]+1, dp[6]+1)=3  (5+5+1)

Complexity

  • Time — O(amount × coins): each amount tries every coin.
  • Space — O(amount): the 1-D dp table.

Common Pitfalls

  • Use amount + 1 as "infinity" so dp[a-c] + 1 never overflows a real int.
  • Return -1 (not the sentinel) when the amount is unreachable.

Full Solution — all languages

class Solution:
    def coinChange(self, nums, target):
        INF = target + 1
        dp = [0] + [INF] * target
        for a in range(1, target + 1):
            for c in nums:
                if c <= a:
                    dp[a] = min(dp[a], dp[a - c] + 1)
        return dp[target] if dp[target] != INF else -1
SensAI
Beta
Tap the mic to stop voice mode