Start learning free

LESSON 245 OF 314 · DYNAMIC PROGRAMMING

Coin Change in Swift: O(n · amount) Dynamic Programming

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 8
    Ctrl + Enter to check

    SWIFT · DYNAMIC PROGRAMMING

    Coin Change in Swift, explained

    Problem overview

    The method coinChange receives an array coins of coin values and an integer amount. It returns the fewest coins that add up to exactly amount, or -1 when no combination does. Each coin value can be used any number of times. There are up to 12 coin values, and amount is between 0 and 10,000. For amount = 0 the answer is 0, because no coins are needed.

    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. With coins = [1, 3, 4] and amount = 6 the answer is 2, from 3 + 3.

    Approach: the fewest coins for every sum up to amount

    A tempting shortcut is to always take the largest coin that still fits. On [1, 3, 4] and 6 it takes 4, then 1, then 1: three coins, while 3 + 3 uses two. Greedy choices can be wrong here. Trying every combination is correct but takes exponential time.

    Dynamic programming solves smaller versions of the question and reuses the answers. 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 that sum needs dp[i - coin] + 1 coins. Trying every coin as the last one and keeping the smallest result gives dp[i]. Fill the table from 1 up to amount, and every entry only needs smaller sums that are already done.

    Two details need a choice of starting values:

    • dp[0] is 0: the sum 0 takes no coins.
    • Every other entry starts at amount + 1. Each coin is worth at least 1, so no sum i needs more than i coins, and amount + 1 can never be a real answer. It works as "not reachable yet", and it is a finite number, so the min comparisons need no special case.

    For coins = [1, 3, 4] and amount = 6, running the code gives these values:

    Sum idp[i]
    00
    11
    22
    31
    41
    52
    62

    The answer is dp[6], which is 2. For coins = [2] and amount = 3, the final table is [0, 4, 1, 4]: sums 1 and 3 keep the starting value 4, which is more than the amount, so the method returns -1.

    Step by step

    1. Create dp as a var array of Int. It has amount + 1 entries, all equal to amount + 1, built with [Int](repeating: amount + 1, count: amount + 1). It is a var because the loops write into it.
    2. Set dp[0] to 0. Every other sum is built on top of this one.
    3. Loop over the sums with i in 1..<amount + 1, smallest first. Write the closing brace right away.
    4. Loop over the coins with coin, trying each as the last coin for the sum i. Write that closing brace too.
    5. Check that the coin fits with coin <= i. A coin worth more than i would make i - coin negative, which is not a valid index.
    6. Update the entry: dp[i] = min(dp[i], dp[i - coin] + 1). It keeps the best result over all coins.
    7. Return -1 when the target stayed unreachable. If dp[amount] is still more than amount, nothing made it. Swift needs the braces around the if body, so it fits on one line as { return -1 }.
    8. Otherwise return dp[amount].

    The solution in Swift

    class Solution {
        func coinChange(_ coins: [Int], _ amount: Int) -> Int {
            var dp = [Int](repeating: amount + 1, count: amount + 1)
            dp[0] = 0
            for i in 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]
        }
    }
    

    The Swift details worth a closer look:

    • Range precedence. 1..<amount + 1 needs no parentheses: the + is evaluated before the range operator, so the range is 1..<(amount + 1).
    • Why half-open. When amount is 0 the range is 1..<1, which is empty, so the loops are skipped and the method returns dp[0], which is 0. The closed range 1...amount would be 1...0. A range can't end below its start, so that stops the program with a run-time error.
    • [Int](repeating:count:). It builds an array with one value repeated. The array is a value type, so assigning into dp changes only dp.
    • Coins as large as 2^31 - 1. An Int holds them without trouble, and the coin <= i check keeps them from being used as an index. For coins = [2147483647] and amount = 10000 the method returns -1.
    • Overflow can't happen. The largest value ever added is amount + 1 plus 1, far below the limit of a 64-bit Int, which is why the "unreachable" marker is a plain number and not Int.max. With Int.max, adding 1 would crash, because Swift traps on overflow.
    • Parameter labels. Both parameters are declared with _, so the call is coinChange([1, 2, 5], 11) without labels.

    Complexity

    Let n be the number of coin values.

    Time: O(n · amount). The outer loop runs amount times, the inner loop runs n times for each, and each step is constant work.

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

    Edge cases and common mistakes

    • Amount 0. Both [1] and [2] with amount 0 return 0.
    • Unreachable amount. [5, 10] with amount 3 returns -1, because both coins are larger than 3.
    • Coins larger than the amount. The coin <= i test skips them, so the index i - coin never goes negative.
    • Greedy by largest coin. It fails on [1, 3, 4] with 6, as shown above.
    • Starting the table at 0. If every entry began at 0, min would never find anything better than 0, and every sum would look free.
    • Forgetting the -1 case. Without the final check, an unreachable amount would return amount + 1.
    • Looping over sums in descending order. Entry i needs smaller entries already finished, so the loop must go upward.

    Testing

    Results from running the reference solution:

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