Start learning free

LESSON 527 OF 671 · DYNAMIC PROGRAMMING

Coin Change in JavaScript: Bottom-Up 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

    JAVASCRIPT · DYNAMIC PROGRAMMING

    Coin Change in JavaScript, 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 if no combination does. Each coin value can be used any number of times, 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 it is -1, because 2s only make even sums. With coins = [1, 3, 4] and amount = 6 it is 2 (3 + 3).

    Approach: the fewest coins for every smaller sum

    The third example shows why a greedy strategy is unsafe. Always taking the largest coin that fits gives 4 + 1 + 1 for 6, which is three coins, while 3 + 3 uses two. Instead, compute the answer for every sum from 0 up to amount.

    Let dp[i] be the fewest coins that make the sum i. Consider the last coin added. If it is coin, the coins before it make i - coin, so the best result through that coin is dp[i - coin] + 1. Trying every coin and keeping the smallest gives dp[i]. Each entry reuses answers for smaller sums that were already computed, which is what makes this dynamic programming. Checking all combinations of coins would take exponential time.

    Why does the last coin work as the way to split the problem? Any combination that makes i has some coin in it. Remove one copy of that coin and what remains is a combination for i - coin. If the whole combination is the fewest possible for i, the remainder must also be the fewest for i - coin, since a smaller one would improve the whole. So the best answer for i always comes from the best answer for some smaller sum, and trying every coin covers every possibility.

    The table needs a marker for "can't be made". Every coin is worth at least 1, so no sum i ever needs more than i coins, and a count of amount + 1 can never be a real answer. The table starts filled with that value, and any entry that still holds it at the end is unreachable.

    Step by step

    1. Create dp with amount + 1 entries, all equal to amount + 1. new Array(amount + 1).fill(amount + 1) does it. The array has one slot per sum from 0 to amount.
    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 from 1 to amount, inclusive. Each dp[i] needs only smaller sums, which are finished by then.
    4. Loop over coins with for...of. Each coin is tried as the last one added to make i.
    5. Check coin <= i. A larger coin doesn't fit in the sum, and i - coin would be a negative index.
    6. Take the minimum: dp[i] = Math.min(dp[i], dp[i - coin] + 1). If i - coin can't be made, dp[i - coin] + 1 is larger than amount, so it never passes for a real answer.
    7. After the loops, return -1 if dp[amount] > amount. Only a sum no combination makes keeps its starting value.
    8. Otherwise return dp[amount]. For amount = 0 the loops don't run and this returns dp[0], which is 0.

    The solution in JavaScript

    class Solution {
        coinChange(coins, amount) {
            const dp = new Array(amount + 1).fill(amount + 1);
            dp[0] = 0;
            for (let i = 1; i <= amount; i++) {
                for (const coin of coins) {
                    if (coin <= i) {
                        dp[i] = Math.min(dp[i], dp[i - coin] + 1);
                    }
                }
            }
            if (dp[amount] > amount) return -1;
            return dp[amount];
        }
    }
    

    A few JavaScript details help here:

    • new Array(k) creates k empty slots, and fill sets every one of them to the same value. Filling with a number is safe, because numbers are copied by value.
    • for (const coin of coins) walks the values of the array. Use for...of for values and not for...in, which walks the indices as strings.
    • dp is a const, but only the variable can't be reassigned: the entries of the array can still change, which is what the loop does.
    • Reading outside an array doesn't throw. dp[-2] gives undefined, and undefined + 1 is NaN, which Math.min turns into NaN. That is why the coin <= i check matters.

    Tracing coins = [1, 3, 4], amount = 6

    The table before the loop is [0,7,7,7,7,7,7]. After each round of the outer loop it looks like this:

    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]
    

    At i = 6 the coin 3 gives dp[3] + 1 = 2, which beats the coin 1 (dp[5] + 1 = 3) and the coin 4 (dp[2] + 1 = 3). The answer is 2.

    Complexity

    With n coins, the outer loop runs amount times and the inner loop n times, so the time is O(n · amount). The table has amount + 1 entries, so the space is O(amount).

    Edge cases and common mistakes

    • Amount 0. The answer is 0, and coinChange([5], 0) returns 0 because the table is just [0].
    • Unreachable sums. coinChange([2], 1) returns -1, and so does coinChange([2], 3). In the second case the table ends as [0,4,1,4]: the entries for 1 and 3 keep the marker value 4.
    • Greedy choice. For [1, 3, 4] and amount 6, taking the largest coin first gives 3 coins, but the answer is 2.
    • Skipping the coin <= i check. The code then reads a negative index, gets undefined, and NaN can end up in the table.
    • Returning dp[amount] directly. For an unreachable amount that returns the marker value (4 in the example above) instead of -1.

    Testing

    Results from the reference solution:

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