Coin change
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Coin change finds the fewest coins (or the number of ways) to make an amount from given coin values. For each amount you try each coin as the last one used and reuse the saved answer for what is left. It is the everyday version of unbounded knapsack.
Practical use cases
- Web app: POS and billing change calculator. A shop billing screen tells the cashier how to return 87 rupees in the fewest notes and coins. The tool builds the best answer for every amount from 1 up to 87 and reads off the one needed. It works even for odd coin sets, where simply grabbing the biggest coin first fails.
- Web app: Game currency shop. A mobile game sells gem packs of unusual sizes and lets players spend exact amounts. The shop checks how few packs make up the gems needed or whether it is possible at all. Players see a clear message instead of an error. For example, if gem packs come in 30, 50 and 80, the shop can tell a player that exactly 70 gems is impossible and suggest the nearest amount that works.
- System: Cash machines and vending machines. An ATM decides which notes to dispense, and a vending machine decides which coins to return. Both must work when some denominations run out. In each of these, the machine must return an exact amount from a limited set of denominations, and the table of best answers for every smaller amount does the work.
The story: Change at the Kirana Counter
Raju's cousin ran a kirana shop with an unusual till: it only held coins of ₹1, ₹5 and ₹6. A customer needed ₹10 back. The new cashier did what feels natural: "Biggest coin first!" He handed over a 6, then four 1-rupee coins. Five coins, and the customer grumbled at the heavy pocket.
Mira peeked into the till and said, "Two 5-rupee coins would have done it." The cashier was stunned. Greedy had failed! Mira explained: "Don't decide the first coin. Ask, what could the last coin be? If the last coin is a 6, I need the best answer for ₹4. If it is a 5, the best for ₹5. If it is a 1, the best for ₹9. Pick the smallest, add one."
She wrote the answers for ₹0, ₹1, ₹2... up to ₹10 on a long strip, each built from earlier cells. That is Coin Change (fewest coins), the textbook unbounded knapsack: the same coin may be used again and again.
How to spot this problem, and where you need it
You must make an exact amount from a set of denominations and need the fewest pieces or the number of ways, and picking the biggest piece first sometimes fails.
Signs you need it
- The problem lists coin or pack values and an amount, and asks for "minimum number of coins" or "number of ways".
- A greedy approach of always taking the largest piece works for some sets but gives wrong answers for others, like coins 1, 3, 4 for amount 6.
- Some amounts may be impossible and you need to report that.
Where to use it in a project
- Change calculation in billing, POS and wallet features.
- Choosing the fewest packs, vouchers or credits to reach an exact amount.
The solution
Create a table with entry 0 equal to 0 coins. For each amount from 1 up to the target, try every coin not larger than the amount, look up the best answer for the amount minus that coin, add one, and keep the smallest. If no coin works, mark the amount impossible. The entry for the target amount is the answer. For counting ways, loop over coins on the outside and add instead of take-the-smallest.
Payoff: Before: a greedy method returning 3 coins for amount 6 with coins 1, 3, 4 when 2 is possible. After: the table finds the true minimum for every amount.
Explain it like I am 8
To pay ₹10, imagine the very last coin you put down. Whatever that coin is, the money left before it was a smaller amount, and you have already written down the best way for that smaller amount. Try each coin, keep the cheapest, add one.
How it works, step by step
- Make a notebook
dp[0..amount].dp[0] = 0(zero coins for zero money); every other cell starts as "impossible" (a huge number). - For each amount
afrom 1 upwards, try every coincwithc ≤ a. - Use the answer already written for the smaller amount:
dp[a] = min(dp[a], dp[a - c] + 1). - Because you may reuse a coin, you simply move up in amounts; no special order for coins is needed.
- At the end, if
dp[amount]is still "impossible", return -1; otherwise it is the answer.
The code in four languages
PHP
<?php
// Fewest coins that add up to $amount, or -1 if impossible.
function coinChange(array $coins, int $amount): int {
$INF = $amount + 1; // anything bigger than any real answer
$dp = array_fill(0, $amount + 1, $INF);
$dp[0] = 0; // 0 coins make 0 rupees
for ($a = 1; $a <= $amount; $a++) {
foreach ($coins as $c) { // try every coin as the LAST coin
if ($c <= $a) {
$dp[$a] = min($dp[$a], $dp[$a - $c] + 1);
}
}
}
return $dp[$amount] >= $INF ? -1 : $dp[$amount];
}
echo coinChange([1, 5, 6], 10), "\n"; // 2 (5 + 5)
echo coinChange([2], 3), "\n"; // -1 (cannot make 3 with 2s)JavaScript
// Fewest coins that add up to amount, or -1 if impossible.
function coinChange(coins, amount) {
const INF = amount + 1; // anything bigger than any real answer
const dp = new Array(amount + 1).fill(INF);
dp[0] = 0; // 0 coins make 0 rupees
for (let a = 1; a <= amount; a++) {
for (const c of coins) { // try every coin as the LAST coin
if (c <= a) {
dp[a] = Math.min(dp[a], dp[a - c] + 1);
}
}
}
return dp[amount] >= INF ? -1 : dp[amount];
}
console.log(coinChange([1, 5, 6], 10)); // 2 (5 + 5)
console.log(coinChange([2], 3)); // -1 (cannot make 3 with 2s)Java
import java.util.*;
public class Main {
// Fewest coins that add up to amount, or -1 if impossible.
static int coinChange(int[] coins, int amount) {
int INF = amount + 1; // anything bigger than any real answer
int[] dp = new int[amount + 1];
Arrays.fill(dp, INF);
dp[0] = 0; // 0 coins make 0 rupees
for (int a = 1; a <= amount; a++) {
for (int c : coins) { // try every coin as the LAST coin
if (c <= a) {
dp[a] = Math.min(dp[a], dp[a - c] + 1);
}
}
}
return dp[amount] >= INF ? -1 : dp[amount];
}
public static void main(String[] args) {
System.out.println(coinChange(new int[]{1, 5, 6}, 10)); // 2 (5 + 5)
System.out.println(coinChange(new int[]{2}, 3)); // -1 (cannot make 3 with 2s)
}
}Go
package main
import "fmt"
// Fewest coins that add up to amount, or -1 if impossible.
func coinChange(coins []int, amount int) int {
INF := amount + 1 // anything bigger than any real answer
dp := make([]int, amount+1)
for i := range dp {
dp[i] = INF
}
dp[0] = 0 // 0 coins make 0 rupees
for a := 1; a <= amount; a++ {
for _, c := range coins { // try every coin as the LAST coin
if c <= a {
dp[a] = min(dp[a], dp[a-c]+1)
}
}
}
if dp[amount] >= INF {
return -1
}
return dp[amount]
}
func main() {
fmt.Println(coinChange([]int{1, 5, 6}, 10)) // 2 (5 + 5)
fmt.Println(coinChange([]int{2}, 3)) // -1 (cannot make 3 with 2s)
}Time: O(amount × coins) · Extra space: O(amount). Each amount tries each coin once; plain recursion would repeat the same sub-amounts exponentially often.
Watch out for
- Trusting the greedy "biggest coin first" idea. It works for some coin sets, but fails for sets like 1, 5, 6.
- Using the largest integer as "impossible" and then adding 1 to it, which overflows in some languages. Use amount + 1 instead.
- Forgetting to return -1 when the amount cannot be formed at all.
Quick check
- Coins 1, 5, 6 and amount 10: what is the fewest coins?
- 5
- 3
- 2
- What does dp[a] mean?
- The biggest coin for amount a
- The fewest coins that make amount a
- How many coins exist
- What is dp[0]?
- 0
- 1
- Impossible