Start learning free

LESSON 245 OF 314 · DYNAMIC PROGRAMMING

Coin Change in Kotlin: 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 8
    Ctrl + Enter to check

    KOTLIN · DYNAMIC PROGRAMMING

    Coin Change in Kotlin, explained

    Problem overview

    The function coinChange receives an IntArray of coin values, coins, and an amount. It returns the fewest coins that add up to exactly amount, or -1 when no combination works. Each coin value can be used any number of times. An amount of 0 needs no coins, so the answer is 0.

    With 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. With coins = [2] and amount = 3 the answer is -1, because a coin of 2 only makes even sums.

    Approach: the fewest coins for every smaller sum

    Greedy thinking, always taking the largest coin that fits, is tempting and wrong. For coins = [1, 3, 4] and amount = 6 it picks 4 + 1 + 1, three coins, while 3 + 3 uses two. Trying every combination of coins is correct but its running time grows exponentially.

    The dynamic programming idea is to answer the question for every sum from 0 up to amount. Let dp[i] be the fewest coins that make the sum i. To make i, some coin is the last one added. If that coin is coin, the coins before it make i - coin, which is a smaller sum whose answer is already in the table. So the candidate is dp[i - coin] + 1. Trying every coin and keeping the smallest candidate gives dp[i].

    The table starts at amount + 1 in every entry. Every coin is worth at least 1, so no sum i ever needs more than i coins, and a count of amount + 1 can't be a real answer. It works as "not reachable yet", and it is large enough that minOf always replaces it with a real count when one exists. A sum that nothing can make keeps this marker, which is how the function knows to return -1.

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

    coins=[1, 3, 4] amount=6 dp=[0, 1, 2, 1, 1, 2, 2]
    

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

    coins=[2] amount=3 dp=[0, 4, 1, 4]
    

    Here the marker is 4. Entries 1 and 3 never improved, and dp[3] is greater than amount, so the answer is -1.

    Step by step

    1. Create dp as IntArray(amount + 1) { amount + 1 }. There are amount + 1 entries, for the sums 0 to amount, and each starts at the marker.
    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..amount. Each entry needs only smaller sums, which are finished by the time the loop reaches i. When amount is 0 the range is empty.
    4. Loop over coins, treating each coin as the last one added to make i.
    5. Check coin <= i. A coin larger than i doesn't fit, and i - coin would be a negative index.
    6. Update dp[i] with minOf(dp[i], dp[i - coin] + 1).
    7. Return -1 if dp[amount] is still greater than amount.
    8. Otherwise return dp[amount].

    The solution in Kotlin

    class Solution {
        fun coinChange(coins: IntArray, amount: Int): Int {
            val dp = IntArray(amount + 1) { amount + 1 }
            dp[0] = 0
            for (i in 1..amount) {
                for (coin in coins) {
                    if (coin <= i) {
                        dp[i] = minOf(dp[i], dp[i - coin] + 1)
                    }
                }
            }
            if (dp[amount] > amount) return -1
            return dp[amount]
        }
    }
    

    The Kotlin details worth a look:

    • IntArray(size) { init }. The lambda runs once per index and returns that entry's starting value. Here it ignores the index and returns amount + 1. IntArray(size) alone would fill the array with zeros, which would wrongly say every sum needs no coins.
    • 1..amount includes both ends. The sum amount itself is computed. When amount is 0, 1..0 is empty, the loops are skipped, and the function returns dp[0], which is 0.
    • for (coin in coins) iterates over the values of an IntArray directly, with no index needed.
    • minOf is in the standard library, so it needs no import. dp[i] is an Int element of an array, assigned with the ordinary =.
    • Guarding i - coin. Without the if, a coin larger than i gives a negative index, and the array access throws an ArrayIndexOutOfBoundsException. This also matters for coin values as large as 2147483647: the check coin <= i is false, so the subtraction never runs.
    • No Int overflow. The largest value stored is the marker plus one, at most 10,002, far from the 32-bit limit.
    • The early return on one line. if (dp[amount] > amount) return -1 needs no braces. Kotlin's if also works as an expression, but here it is used as a statement.

    Complexity

    Let n be the number of coins.

    Time: O(n * amount). The outer loop runs amount times and the inner loop runs n times for each, with constant work inside.

    Space: O(amount). The table has amount + 1 entries, and nothing else grows.

    Edge cases and common mistakes

    • Amount 0. coins = [1] with amount = 0 returns 0.
    • Impossible amounts. coins = [5, 10] with amount = 3 returns -1, and so does coins = [2147483647] with amount = 10000.
    • Greedy choice. The largest-coin-first shortcut gives 3 coins for [1, 3, 4] and 6 where the table finds 2.
    • Starting the table at 0. Then minOf keeps 0 for every entry and the function reports that no coins are needed.
    • Starting the table at Int.MAX_VALUE. Then dp[i - coin] + 1 overflows and wraps to Int.MIN_VALUE for an unreachable sum, which looks like the smallest count of all. The marker amount + 1 avoids this.
    • Forgetting -1. Returning dp[amount] directly would give amount + 1 for impossible inputs, such as 4 for [2] and 3.
    • Walking down from amount. The table must be filled from small sums up, so that dp[i - coin] is final when it is read.

    Testing

    These inputs give the following results from 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 = [7], amount = 14 gives 2.
    • coins = [186, 419, 83, 408], amount = 6249 gives 20.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free