Algo-Sim › Dynamic Programming

Coin Change

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Fewest coins to make an amount: dp[a] is one more than the best dp[a − coin] over every coin that fits.

Problem

Given coin denominations coins (each available in unlimited supply) and an amount, return the fewest coins that add up to exactly amount, or -1 if it cannot be made.

Constraints

Edge cases to test

Follow-up questions

Why does greedy fail?
With coins [1, 3, 4] and amount 6, greedy takes 4 + 1 + 1 but 3 + 3 is better. Greedy works only for canonical systems like real currencies.
Is there a BFS view?
Each amount is a node and each coin an edge; the fewest coins is the shortest path from 0: O(amount · coins).

Solution

Java

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

Python

def coin_change(coins, amount):
    dp = [amount + 1] * (amount + 1)
    dp[0] = 0
    for a in range(1, amount + 1):
        for coin in coins:
            if coin <= a:
                dp[a] = min(dp[a], dp[a - coin] + 1)
    return -1 if dp[amount] > amount else dp[amount]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int coinChange(vector<int> &coins, int amount) {
        vector<int> dp = vector<int>(amount + 1);
        fill(dp.begin(), dp.end(), amount + 1);
        dp[0] = 0;
        for (int a = 1; a <= amount; a++) {
            for (int coin : coins) {
                if (coin <= a) {
                    dp[a] = std::min(dp[a], dp[a - coin] + 1);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }
};

More Dynamic Programming problems