Start learning free

LESSON 245 OF 314 · DYNAMIC PROGRAMMING

Coin Change in C++: Bottom-Up Dynamic Programming, O(n · amount)

Practice O(n · amount) Read the full explanation

You get a vector 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

    C++ · DYNAMIC PROGRAMMING

    Coin Change in C++, explained

    Problem overview

    The method coinChange receives a vector 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 as often as you like.

    For coins = [1, 2, 5] and amount = 11 the answer is 3, from 5 + 5 + 1. For coins = [2] and amount = 3 the answer is -1, because 2s only make even sums. When amount is 0 the answer is 0: no coins are needed.

    Approach: the best answer for every smaller sum

    A tempting shortcut is to always take the largest coin that still fits. With coins = [1, 3, 4] and amount = 6 it picks 4, then 1, then 1: three coins, while 3 + 3 uses two. Greedy choices can fail here, so the solution compares every option instead.

    Think about the last coin added to make a sum i. If that coin is coin, the coins before it make the sum i - coin, and the total is one more than the best for i - coin. Trying every coin as the last one and keeping the smallest result gives the best answer for i:

    dp[i] = min(dp[i - coin] + 1) over all coins with coin <= i

    The table dp is filled from the sum 0 upward, so every entry it needs is ready by then. This is dynamic programming: each answer reuses the answers for smaller sums.

    For sums that can't be made, the table needs 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 with that value everywhere, and an entry that keeps it at the end means "impossible".

    Step by step

    1. Create dp with amount + 1 elements, all equal to amount + 1. The constructor takes the size first and then the value of every element. dp[i] will be the fewest coins for the sum i.
    2. Set dp[0] to 0. The sum 0 takes no coins, and every other sum is built on top of it.
    3. Loop over the sums i from 1 to amount inclusive. Each dp[i] needs only smaller sums, which are finished by then.
    4. Loop over the coins with a range-based for. 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 min(dp[i], dp[i - coin] + 1). If i - coin can't be made, dp[i - coin] + 1 is already more than amount, so it never looks like a real answer.
    7. Return -1 if dp[amount] is still greater than amount: only an impossible sum keeps its starting value.
    8. Otherwise return dp[amount]. When amount is 0 the loops don't run and this returns dp[0], which is 0.

    The solution in C++

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

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

    sum:  0 1 2 3 4 5 6
    dp:   0 1 2 1 1 2 2
    

    Sum 6 is reached from 3 (dp is 1) with a coin of 3, giving 2 coins. For coins = [2] and amount = 3 the table is:

    sum:  0 1 2 3
    dp:   0 4 1 4
    

    The entries for 1 and 3 still hold the marker 4 (amount + 1), so the function returns -1.

    The C++ details:

    • vector<int> dp(amount + 1, amount + 1) uses the constructor (count, value). Writing it with braces, {amount + 1, amount + 1}, would instead make a vector of two elements.
    • for (int coin : coins) copies each value, which is cheap for an int.
    • Why the marker doesn't overflow. dp[i - coin] + 1 is at most amount + 2, far below the 32-bit limit. Using INT_MAX as the marker would overflow on the + 1, and signed overflow is undefined behaviour in C++.
    • Huge coins are safe. A coin can be as large as 2^31 - 1. The check coin <= i skips it before any subtraction, and i is at most 10,000.

    Complexity

    Time: O(n · amount), where n is the number of coins. There are amount sums, and each tries every coin with constant work.

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

    Edge cases and common mistakes

    • amount = 0. The result is 0, with coins = [1, 2, 5] or any other coins.
    • No combination. coins = [5] with amount = 3 returns -1: no coin fits, so dp[3] keeps its marker.
    • A coin larger than the amount. Without the coin <= i check, dp[i - coin] would read a negative index, which is undefined behaviour.
    • Greedy by the largest coin. For [1, 3, 4] and 6, taking 4 first leads to 3 coins; the table finds 2.
    • A coin that skips some sums. coins = [2, 5] with amount = 11 returns 4 (2 + 2 + 2 + 5). The sums 1 and 3 are impossible, and the table handles that through their markers.
    • Returning dp[amount] without the check. For an impossible amount it would return the marker, amount + 1, instead of -1.

    Testing

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