Start learning free

LESSON 245 OF 314 · DYNAMIC PROGRAMMING

Coin Change in Python: Bottom-Up Dynamic Programming

Practice O(n · amount) Read the full explanation

You get a list coins of coin values and an integer amount.

Return the smallest number of coins that add up to exactly amount.

You can use each coin value as many times as you like. If no mix of coins makes amount, return -1.

 

Example 1:

Input: coins = [2, 5, 10], amount = 27
Output: 4
Explanation: 27 = 10 + 10 + 5 + 2.
No three coins add up to 27.

Example 2:

Input: coins = [4, 6], amount = 9
Output: -1
Explanation: Both coin values are even.
So every sum of them is even.
9 is odd, so no mix of coins makes it.

Example 3:

Input: coins = [1, 5, 6, 9], amount = 11
Output: 2
Explanation: 11 = 5 + 6.
9 + 1 + 1 also makes 11, but that is three coins.

 

Constraints:

  • coins holds 1 to 12 values.
  • Each value is from 1 to 231 - 1.
  • amount is from 0 to 10,000.
  • For amount = 0, the answer is 0 (no coins are needed).
STEP 1 OF 8
    Ctrl + Enter to check

    PYTHON · DYNAMIC PROGRAMMING

    Coin Change in Python, explained

    Problem overview

    The method coinChange receives a list coins of coin values and an integer amount. It returns the fewest coins that add up to exactly amount, or -1 if no combination does. Each value can be used any number of times. For an amount of 0 the answer is 0.

    With coins = [1, 2, 5] and amount = 11 the answer is 3, from 5 + 5 + 1. With coins = [2] and amount = 3 the answer is -1, since 2s only make even sums.

    Approach: the fewest coins for every smaller sum

    The tempting shortcut is greedy: always take the largest coin that fits. It fails here: for coins = [1, 3, 4] and amount = 6 greedy takes 4 + 1 + 1, three coins, while 3 + 3 uses two. Trying every combination is far too slow, as the number of combinations grows very fast with the amount.

    Dynamic programming solves the problem for every sum from 0 up to amount. Let dp[i] be the fewest coins that make the sum i. If the last coin added is coin, the coins before it make i - coin, so the candidate is dp[i - coin] + 1. Trying every coin and keeping the smallest candidate gives dp[i]. Each entry reuses entries for smaller sums, which are already filled.

    Step by step

    1. Create dp as [amount + 1] * (amount + 1): one entry per sum from 0 to amount. Every coin is worth at least 1, so no sum i needs more than i coins. A count of amount + 1 can never be real, so it marks a sum that can't be made (yet).
    2. Set dp[0] = 0. The sum 0 takes no coins, and every other entry is built on top of it.
    3. Loop i over range(1, amount + 1), from the smallest sum up, so the smaller sums are done when i is reached.
    4. Loop over coins with coin: each coin is tried as the last one added.
    5. Check coin <= i. A coin worth more than i doesn't fit, and i - coin would be a negative index.
    6. Update dp[i] to min(dp[i], dp[i - coin] + 1). If i - coin can't be made, dp[i - coin] + 1 is more than amount too, so it never passes for a real answer.
    7. If dp[amount] > amount, return -1. Only a sum no combination makes keeps its starting value.
    8. Otherwise return dp[amount]. For amount = 0 the loops don't run and this returns dp[0], which is 0.

    The solution in Python

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

    For coins = [1, 3, 4] and amount = 6 the finished table is:

    [0, 1, 2, 1, 1, 2, 2]
    

    Reading it, dp[6] = 2 comes from dp[3] + 1. For coins = [2] and amount = 3 the table is:

    [0, 4, 1, 4]
    

    The entries 4 are the "can't be made" marker, which is amount + 1. The last one is greater than 3, so the function returns -1.

    Python details worth knowing:

    • [amount + 1] * (amount + 1) repeats one integer, which is safe because integers are immutable. Repeating a list of lists this way is a different matter, because the rows would be the same object.
    • Python integers have no overflow, so using amount + 1 as "infinity" is safe. float('inf') would also work but turns the table into floats.
    • min returns the smaller of its two arguments.

    Complexity

    Time: O(n * amount), where n is the number of coin values: the two nested loops do constant work per pair. Space: O(amount) for the table.

    Edge cases and common mistakes

    • Amount 0. coinChange([1], 0) returns 0, with no coins used.
    • Unreachable amounts. coinChange([3, 7], 5) returns -1.
    • A coin equal to the amount. coinChange([5], 5) returns 1.
    • Coins larger than the amount. Without the coin <= i check, dp[i - coin] uses a negative index, which Python reads from the end of the list instead of raising an error. The result is silently wrong.
    • Starting entries at 0. Then min would always keep 0 and every sum would look free.
    • Greedy. Taking the largest coin first gives 3 for [1, 3, 4] and 6, but the answer is 2.

    Testing

    • coins = [1, 2, 5], amount = 11 gives 3.
    • coins = [2], amount = 3 gives -1.
    • coins = [1, 3, 4], amount = 6 gives 2.
    • coins = [1], amount = 0 gives 0.
    • coins = [2, 5], amount = 7 gives 2.
    • coins = [3, 7], amount = 5 gives -1.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free