Start learning free

LESSON 245 OF 314 · DYNAMIC PROGRAMMING

Coin Change in Scala: Bottom-Up Dynamic Programming, 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 8
    Ctrl + Enter to check

    SCALA · DYNAMIC PROGRAMMING

    Coin Change in Scala, explained

    Problem overview

    The method coinChange receives an array of coin values, coins, and a target 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 often as you like, and an amount of 0 needs 0 coins.

    With coins = [1, 2, 5] and amount = 11 the answer is 3: 5 + 5 + 1. With coins = [2] and amount = 3 the answer is -1, because coins of 2 only make even sums.

    Approach: the fewest coins for every smaller sum

    Always taking the largest coin that fits looks natural, but it fails. For coins = [1, 3, 4] and amount = 6 it picks 4 + 1 + 1, three coins, while 3 + 3 uses two. Trying every combination is too slow, so we solve the same question 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 best way to use that coin is dp(i - coin) + 1. Try each coin that fits and keep the smallest result. Because i - coin is always smaller than i, filling the table from small sums to large ones means every value we need is already there.

    For sums we can't make we need a marker. Every coin is worth at least 1, so no sum i ever needs more than i coins, and amount + 1 can never be a real answer. The table starts filled with amount + 1, meaning "can't make this yet". If dp(amount) is still above amount at the end, no combination exists.

    Step by step

    1. Create dp with Array.fill(amount + 1)(amount + 1): amount + 1 entries, each equal to amount + 1.
    2. Set dp(0) to 0. The sum 0 takes no coins, and every other entry is built on top of it.
    3. Loop i over 1 to amount. This fills the table from the smallest sum up. When amount is 0 the range is empty.
    4. Loop over coins. Each coin is tried as the last one added to make i.
    5. Check coin <= i. A coin worth more than i can't be part of the sum, and i - coin would be a negative index.
    6. Update dp(i) to math.min(dp(i), dp(i - coin) + 1). If i - coin can't be made, dp(i - coin) + 1 is above amount as well, so it never looks like a real answer.
    7. Return -1 if dp(amount) is still above amount. Only a sum that nothing makes keeps its starting value.
    8. Otherwise end with dp(amount).

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

    0 1 2 1 1 2 2

    The entry at index 6 is 2, which is 3 + 3. For coins = [2] and amount = 3 the table ends as 0 4 1 4: sum 2 is reachable with one coin, but sum 3 keeps its marker 4, which is above 3, so the method returns -1.

    The solution in Scala

    class Solution {
        def coinChange(coins: Array[Int], amount: Int): Int = {
            val dp = Array.fill(amount + 1)(amount + 1)
            dp(0) = 0
            for (i <- 1 to amount) {
                for (coin <- coins) {
                    if (coin <= i) {
                        dp(i) = math.min(dp(i), dp(i - coin) + 1)
                    }
                }
            }
            if (dp(amount) > amount) return -1
            dp(amount)
        }
    }
    

    The Scala details worth a closer look:

    • Array.fill(size)(value). It takes two parameter lists: the size first, then the value to repeat. The result is an Array[Int], which is mutable even though it is held in a val. The val keeps the name pointing to the same array, and dp(i) = ... changes its contents.
    • Assignment with parentheses. dp(0) = 0 is how Scala writes an array element update, in the same style as reading dp(i).
    • Generators. i <- 1 to amount runs i through the range including amount, and coin <- coins runs through the array's elements.
    • Early return. if (dp(amount) > amount) return -1 leaves the method at once with the declared Int result. Without it, the last expression, dp(amount), is the normal result.
    • Large coin values. A coin can be as large as 2^31 - 1, the biggest Int. The check coin <= i comes first, so i - coin is never computed for such a coin, and coinChange(Array(2147483647), 5) returns -1 with no overflow.

    Complexity

    Time: O(n · amount), where n is the number of coins. The two nested loops make amount times n constant-time updates.

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

    Edge cases and common mistakes

    • Amount 0. The loops don't run and the method returns dp(0), which is 0, for any coins.
    • Impossible amounts. coins = [5, 10] with amount = 3 returns -1: no coin fits, so dp(3) keeps its starting value 4.
    • Greedy choice. Taking the largest coin first gives three coins for [1, 3, 4] and 6, while the table finds two.
    • Forgetting the coin <= i check. For a coin larger than i the index i - coin is negative, and the program throws an ArrayIndexOutOfBoundsException.
    • Using 0 as the "impossible" marker. Then math.min would always keep 0 and report that every sum needs no coins. The marker must be larger than any real answer.
    • Using Int.MaxValue as the marker. Adding 1 to it wraps to a large negative number and corrupts the minimum. amount + 1 is large enough and can't overflow.

    Testing

    • coins = [1, 2, 5], amount = 11 gives 3.
    • coins = [2], amount = 3 gives -1.
    • coins = [1, 3, 4], amount = 6 gives 2.
    • coins = [2, 5, 10, 1], amount = 27 gives 4.
    • coins = [186, 419, 83, 408], amount = 6249 gives 20.
    • coins = [1], amount = 0 gives 0.
    • coins = [5, 10], amount = 3 gives -1.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free