Start learning free

LESSON 245 OF 314 · DYNAMIC PROGRAMMING

Coin Change in Go: Bottom-Up Dynamic Programming in O(n · amount)

Practice O(n · amount) Read the full explanation

You get an array 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 10
    Ctrl + Enter to check

    GO · DYNAMIC PROGRAMMING

    Coin Change in Go, explained

    Problem overview

    The function coinChange receives a slice coins of coin values and an integer amount. It returns the fewest coins that add up to exactly amount, or -1 when no combination works. Each coin value can be used as many times as you like. When amount is 0 the answer is 0.

    For coins = [1, 2, 5] and amount = 11, the answer is 3: 5 + 5 + 1. Two coins can't do it, since the largest sum of two coins is 10. For coins = [2] and amount = 3 the answer is -1, because 2s only make even sums.

    Approach: the fewest coins for every sum up to amount

    Taking the largest coin that fits looks natural, but it isn't always right. With coins = [1, 3, 4] and amount = 6 it picks 4 + 1 + 1, three coins, while 3 + 3 uses two.

    Trying every combination works but is far too slow. Dynamic programming gives a better route. 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 cost is dp[i - coin] + 1. Trying every coin as the last one and keeping the smallest result gives dp[i]. Filling the table from small sums to large ensures that dp[i - coin] is ready when it is needed.

    Sums that can't be made need a marker. Every coin is worth at least 1, so no sum i needs more than i coins, and a count of amount + 1 can never be a real answer. It works as "impossible, so far". It also behaves well in the formula: if i - coin can't be made, dp[i - coin] + 1 is larger than amount too, so it never passes for a real result.

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

    start [0 7 7 7 7 7 7]
    i = 1 [0 1 7 7 7 7 7]
    i = 2 [0 1 2 7 7 7 7]
    i = 3 [0 1 2 1 7 7 7]
    i = 4 [0 1 2 1 1 7 7]
    i = 5 [0 1 2 1 1 2 7]
    i = 6 [0 1 2 1 1 2 2]

    The last entry is 2, the answer. The 7 at the start is amount + 1.

    Step by step

    1. Create dp with make([]int, amount+1): one slot for each sum from 0 to amount, filled with zeros.
    2. Loop over dp with range, keeping only the index i.
    3. Set every dp[i] to amount + 1, the "can't make it yet" marker.
    4. Set dp[0] to 0. The sum 0 takes no coins, and every other sum is built on top of it.
    5. Loop over the sums i from 1 to amount, inclusive. Each one needs only smaller sums, which are already done.
    6. Loop over coins with for _, coin := range coins. The _ discards the index. Each coin is tried as the last one added to make i.
    7. Check coin <= i. A larger coin doesn't fit in the sum, and i - coin would be a negative index.
    8. Update dp[i] to the smaller of its current value and dp[i-coin]+1.
    9. If dp[amount] is still above amount, return -1: only a sum that no combination makes keeps its starting value.
    10. Otherwise return dp[amount]. For amount = 0 the loops don't run and this returns dp[0], which is 0.

    The solution in Go

    func coinChange(coins []int, amount int) int {
        dp := make([]int, amount+1)
        for i := range dp {
            dp[i] = amount + 1
        }
        dp[0] = 0
        for i := 1; i <= amount; i++ {
            for _, coin := range coins {
                if coin <= i {
                    dp[i] = min(dp[i], dp[i-coin]+1)
                }
            }
        }
        if dp[amount] > amount {
            return -1
        }
        return dp[amount]
    }
    

    The Go details worth a closer look:

    • make zero-fills. make([]int, 3) is [0 0 0]. That is why the code writes amount + 1 into every slot afterwards.
    • for i := range dp gives indexes only. With two names, for i, v := range dp, you would get the value as well. for _, coin := range coins does the opposite: it throws away the index and keeps the value.
    • The built-in min. Since Go 1.21, min and max are built in, with no import. The lessons use Go 1.22.
    • Braces are required. Even a one-statement if needs { }, and the opening brace has to be on the same line as the condition.
    • Large coin values are safe. Coins can be as large as 2147483647 (2^31 - 1), which fits in Go's 64-bit int. Such a coin never passes the coin <= i check, since i is at most 10000.

    Complexity

    Time: O(n · amount), where n is the number of coins. The outer loop runs amount times and the inner loop tries all n coins each time.

    Space: O(amount). The table has amount + 1 entries.

    Edge cases and common mistakes

    • Amount 0. The answer is 0 coins. dp has one entry, dp[0] = 0, and it is returned.
    • Skipping the coin <= i check. Then dp[i-coin] uses a negative index. In Go that stops the program with a run-time panic (index out of range [-1]).
    • Starting the table at 0. If every slot started at 0, min would never replace it, and every sum would look like it takes no coins.
    • Starting with a huge value such as math.MaxInt. Then dp[i-coin]+1 overflows and wraps around to a very negative number, which min picks. The marker amount + 1 avoids this.
    • Greedy choice. Always taking the largest coin fails on [1, 3, 4] with 6.
    • Using i < amount. The loop would leave dp[amount] at its marker, and the function would return -1 for every amount above 0.

    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 = [5, 10], amount = 3 gives -1.
    • coins = [2147483647], amount = 10000 gives -1.
    • coins = [186, 419, 83, 408], amount = 6249 gives 20.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free