Start learning free

LESSON 527 OF 671 · DYNAMIC PROGRAMMING

Coin Change in Java: 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

    JAVA · DYNAMIC PROGRAMMING

    Coin Change in Java, explained

    Problem overview

    The method coinChange receives an int[] of coin values and an int 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, from 5 + 5 + 1. For coins = [2] and amount = 3 it is -1, because 2s only make even sums.

    Approach: the fewest coins for every sum up to amount

    A tempting shortcut is to always take the largest coin that still fits. It fails for coins = [1, 3, 4] and amount = 6: greedy takes 4 + 1 + 1, three coins, but 3 + 3 uses two. Trying every combination is correct but far too slow, so we solve smaller versions of the problem and reuse them.

    Let dp[i] be the fewest coins that make the sum i. Suppose the last coin added was coin. Then the coins before it make the sum i - coin, using dp[i - coin] coins, so the total is dp[i - coin] + 1. We don't know which coin comes last, so we try every coin and keep the smallest result. Each entry depends only on smaller sums, so filling the table from 1 up to amount always finds the needed entries ready.

    Sums that can't be made 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. We start every entry at amount + 1 to mean "not reachable yet". An unreachable dp[i - coin] plus 1 still exceeds amount, so it never beats a real answer.

    The table for coins = [1, 2, 5] and amount = 11, entries 0 to 11, is:

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

    The last entry is 3, the answer. For coins = [1, 3, 4] and amount = 6 it is [0, 1, 2, 1, 1, 2, 2], so dp[6] is 2. For coins = [2] and amount = 3 it is [0, 4, 1, 4]: the 4s are the "unreachable" marker, and dp[3] = 4 is above 3, so the answer is -1.

    The table keeps the minimum over several choices, rather than a sum of counts. The coins may come in any order and may repeat, so the table never has to remember which coins were used, only how many. That is what makes it small: amount + 1 numbers describe every sub-problem.

    Step by step

    1. Create dp, an int array of size amount + 1 so that index amount exists, and fill it with amount + 1 using Arrays.fill. A new int array starts with zeros, which would claim every sum takes no coins.
    2. Set dp[0] = 0. The sum 0 needs no coins, and every other sum is built on top of it.
    3. Loop i from 1 to amount inclusive, smallest sum first.
    4. Loop over the coins with an enhanced for. Each coin is tried as the last one added to make i.
    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 the smaller of its current value and dp[i - coin] + 1, using Math.min.
    7. After the loops, test dp[amount] > amount and return -1: the sum was never reached.
    8. Otherwise return dp[amount].

    The solution in Java

    class Solution {
        public int coinChange(int[] coins, int amount) {
            int[] dp = new int[amount + 1];
            Arrays.fill(dp, amount + 1);
            dp[0] = 0;
            for (int i = 1; i <= amount; i++) {
                for (int coin : coins) {
                    if (coin <= i) {
                        dp[i] = Math.min(dp[i], dp[i - coin] + 1);
                    }
                }
            }
            if (dp[amount] > amount) return -1;
            return dp[amount];
        }
    }
    

    Java details worth noticing:

    • Arrays.fill comes from java.util.Arrays and sets every entry of an array to one value. Outside the lesson's editor you need import java.util.Arrays; at the top of the file.
    • The enhanced for loop. for (int coin : coins) visits each element by value, and no index is needed because only the coin values matter.
    • One-line if. if (dp[amount] > amount) return -1; works without braces. Braces are still safer when you later add a second statement.
    • No overflow. The marker is at most amount + 1, about 10,001, and the + 1 never gets near the int limit. Coin values as large as 2^31 - 1 are fine too, since coin <= i keeps them out of the arithmetic unless they fit within amount.

    Complexity

    Time: O(n · amount), where n is the number of coins. The outer loop runs amount times, the inner one n times, and each pass does constant work.

    Space: O(amount) for the table of amount + 1 integers.

    Edge cases and common mistakes

    • amount = 0. The loops don't run, and the method returns dp[0], which is 0. For coins = [5] and amount = 0 it returns 0, not -1.
    • Impossible amounts. For coins = [3, 7] and amount = 5 it returns -1, since no combination of 3s and 7s makes 5.
    • Greedy choice. Taking the biggest coin first gives 3 coins for [1, 3, 4] and 6, while the answer is 2.
    • Forgetting the marker. Leaving the array at zeros makes every sum look free, and Math.min would always pick 0.
    • Using Integer.MAX_VALUE as the marker without care. dp[i - coin] + 1 then overflows to a large negative number and wins every comparison. That is why this solution uses amount + 1.
    • Skipping the coin <= i check. It leads to an ArrayIndexOutOfBoundsException as soon as a coin is larger than the current sum.

    Testing

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