Minimum number of coins
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Making change with the fewest coins by always taking the biggest coin that still fits works perfectly for ordinary currencies like rupee notes and coins. For odd coin sets it can fail, which is a useful lesson on when greedy is safe.
Practical use cases
- Web app: ATM or cash dispenser logic. A banking back end decides which notes to give for a withdrawal of Rs 3,700. It takes as many 2,000s as fit, then 500s, then 200s, and so on, giving the fewest notes so the machine does not run out of small ones too soon.
- Web app: POS and billing screen change helper. A shop billing page tells the cashier which notes and coins to return for a bill. Greedy picking shows the shortest handover and avoids fumbling at the counter. Queues move faster and the till is less likely to run out of small coins.
- Web app: Game currency or reward breakdown. A game or loyalty app turns 1,375 points into the fewest vouchers of 500, 100, 50 and 5 points, keeping the wallet screen tidy.
- System: When greedy fails. With coins 1, 3 and 4, making 6 greedily gives 4+1+1, three coins, whereas 3+3 uses two. For such sets, dynamic programming is needed. So always test unusual denominations before trusting greedy.
The story: Raju's Change Box
Every evening Raju counted the day's money at his chai stall and gave change for big notes. His box held coins and notes of ₹1, ₹2, ₹5, ₹10, ₹20, ₹50, ₹100 and ₹500. A customer paid a big note, and Raju owed back ₹93.
Raju's old way: grab many small coins until the amount adds up. Ninety-three ₹1 coins! The customer's hands were full, and the queue behind him groaned. "Use fewer pieces," said Mira.
So Raju started with the biggest piece that still fits. ₹93 needs ₹50 (left ₹43). Then ₹20 (left ₹23), another ₹20 (left ₹3), then ₹2 (left ₹1) and ₹1. Five pieces. Very quick!
Then Grandpa Bhaskar told them a surprise: "In a strange country with coins of 1, 3 and 4, giving back 6 this way means 4+1+1, three coins. But 3+3 is only two!" Greedy works for money systems like ours, not for every set of coins. Raju learned to trust his coin box and to be careful with unusual ones.
How to spot this problem, and where you need it
You must pay or dispense an exact amount using the fewest pieces, and you want to know whether simply taking the largest piece each time gives the best answer.
Signs you need it
- The wording is "fewest coins or notes for this amount" with an unlimited supply of each denomination.
- The denominations are a normal currency set where each is roughly a multiple of smaller ones, like 1, 2, 5, 10, 20, 50.
- A hand example with your coin set works with biggest-first, but you have not tried tricky sets.
Where to use it in a project
- Cash dispenser, vending machine and billing-counter logic that returns notes and coins for an exact amount.
- Reward, voucher and points-conversion screens in shopping and wallet apps.
The solution
Sort the denominations from biggest to smallest. For each one, take as many as fit into the remaining amount (integer division), subtract their total, and move to the next. Stop when the remainder is zero. For standard currencies this is provably the fewest. If you accept unusual denominations, test it first or use dynamic programming, which tries all possibilities in a table.
Payoff: Before: dispensing Rs 3,700 as thirty-seven 100 notes. After: one 2,000, three 500s and one 200, five notes in total.
Explain it like I am 8
To pay with the fewest coins, grab the biggest coin that is not too big, then repeat for what is left. It is like emptying a big bucket with the biggest scoop first. With normal coins that is perfect. With strange coin sizes, a smaller scoop might have fit better at the end!
How it works, step by step
- Sort the coins from biggest to smallest.
- For each coin, give as many copies as fit into the amount left.
- Subtract what you gave and move to the next smaller coin.
- Stop when the amount left is zero. Count the pieces you gave.
- Only trust this for "friendly" coin systems like the Indian ones. For odd sets, use dynamic programming.
The code in four languages
PHP
<?php
// Greedy change: biggest coin first. Works for "friendly" coin sets like Indian rupees.
function greedyCoins(array $coins, int $amount): array {
rsort($coins); // biggest first
$given = [];
foreach ($coins as $c) {
while ($amount >= $c) { // take this coin while it still fits
$given[] = $c;
$amount -= $c;
}
}
return $given;
}
// Careful method (dynamic programming): fewest coins for every amount up to the target.
function bestCount(array $coins, int $amount): int {
$dp = array_fill(0, $amount + 1, $amount + 1); // "infinity"
$dp[0] = 0;
for ($a = 1; $a <= $amount; $a++) {
foreach ($coins as $c) {
if ($c <= $a) $dp[$a] = min($dp[$a], $dp[$a - $c] + 1);
}
}
return $dp[$amount] > $amount ? -1 : $dp[$amount];
}
$rupees = [1, 2, 5, 10, 20, 50, 100, 500, 2000];
echo implode(' + ', greedyCoins($rupees, 93)) . PHP_EOL; // 50 + 20 + 20 + 2 + 1
echo "Odd coins {1,3,4}, amount 6: greedy " . count(greedyCoins([1, 3, 4], 6))
. " vs best " . bestCount([1, 3, 4], 6) . PHP_EOL; // greedy 3 vs best 2JavaScript
// Greedy change: biggest coin first. Works for "friendly" coin sets like Indian rupees.
function greedyCoins(coins, amount) {
coins = [...coins].sort((a, b) => b - a); // biggest first
const given = [];
for (const c of coins) {
while (amount >= c) { // take this coin while it still fits
given.push(c);
amount -= c;
}
}
return given;
}
// Careful method (dynamic programming): fewest coins for every amount up to the target.
function bestCount(coins, amount) {
const dp = new Array(amount + 1).fill(amount + 1); // "infinity"
dp[0] = 0;
for (let a = 1; a <= amount; a++) {
for (const c of coins) {
if (c <= a) dp[a] = Math.min(dp[a], dp[a - c] + 1);
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
const rupees = [1, 2, 5, 10, 20, 50, 100, 500, 2000];
console.log(greedyCoins(rupees, 93).join(' + ')); // 50 + 20 + 20 + 2 + 1
console.log("Odd coins {1,3,4}, amount 6: greedy " + greedyCoins([1, 3, 4], 6).length
+ " vs best " + bestCount([1, 3, 4], 6)); // greedy 3 vs best 2Java
import java.util.*;
public class Main {
// Greedy change: biggest coin first. Works for "friendly" coin sets like Indian rupees.
static List<Integer> greedyCoins(int[] coinList, int amount) {
int[] coins = coinList.clone();
Arrays.sort(coins); // smallest first ...
List<Integer> given = new ArrayList<>();
for (int i = coins.length - 1; i >= 0; i--) { // ... so walk backwards: biggest first
int c = coins[i];
while (amount >= c) { // take this coin while it still fits
given.add(c);
amount -= c;
}
}
return given;
}
// Careful method (dynamic programming): fewest coins for every amount up to the target.
static int bestCount(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1); // "infinity"
dp[0] = 0;
for (int a = 1; a <= amount; a++) {
for (int c : coins) {
if (c <= a) dp[a] = Math.min(dp[a], dp[a - c] + 1);
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
public static void main(String[] args) {
int[] rupees = {1, 2, 5, 10, 20, 50, 100, 500, 2000};
var change = greedyCoins(rupees, 93);
StringJoiner sj = new StringJoiner(" + ");
for (int c : change) sj.add(String.valueOf(c));
System.out.println(sj); // 50 + 20 + 20 + 2 + 1
System.out.println("Odd coins {1,3,4}, amount 6: greedy " + greedyCoins(new int[]{1, 3, 4}, 6).size()
+ " vs best " + bestCount(new int[]{1, 3, 4}, 6)); // greedy 3 vs best 2
}
}Go
package main
import (
"fmt"
"slices"
"strconv"
"strings"
)
// greedyCoins gives change with the biggest coin first. Works for "friendly" coin sets like Indian rupees.
func greedyCoins(coinList []int, amount int) []int {
coins := slices.Clone(coinList)
slices.Sort(coins)
slices.Reverse(coins) // biggest first
var given []int
for _, c := range coins {
for amount >= c { // take this coin while it still fits
given = append(given, c)
amount -= c
}
}
return given
}
// bestCount is the careful method (dynamic programming): fewest coins for every amount up to the target.
func bestCount(coins []int, amount int) int {
dp := make([]int, amount+1)
for i := range dp {
dp[i] = amount + 1 // "infinity"
}
dp[0] = 0
for a := 1; a <= amount; a++ {
for _, c := range coins {
if c <= a {
dp[a] = min(dp[a], dp[a-c]+1)
}
}
}
if dp[amount] > amount {
return -1
}
return dp[amount]
}
func main() {
rupees := []int{1, 2, 5, 10, 20, 50, 100, 500, 2000}
var parts []string
for _, c := range greedyCoins(rupees, 93) {
parts = append(parts, strconv.Itoa(c))
}
fmt.Println(strings.Join(parts, " + ")) // 50 + 20 + 20 + 2 + 1
fmt.Println("Odd coins {1,3,4}, amount 6: greedy", len(greedyCoins([]int{1, 3, 4}, 6)),
"vs best", bestCount([]int{1, 3, 4}, 6)) // greedy 3 vs best 2
}Time: O(n log n + k) · Extra space: O(k). n = number of coin types (sorting them), k = coins handed out. The careful DP version costs O(amount × n).
Watch out for
- Assuming greedy works for any coin set. With {1, 3, 4} and amount 6 it gives 3 coins when 2 is possible.
- Forgetting that some amounts may be impossible with some coin sets (for example only even coins and an odd amount).
- Not sorting the coins from biggest to smallest first.
Quick check
- Greedy change for ₹93 with Indian coins gives how many pieces?
- 5
- 4
- 6
- With coins {1, 3, 4} and amount 6, what is the best answer?
- 3 coins (4+1+1)
- 1 coin
- 2 coins (3+3)
- What should you use when greedy is not safe for a coin set?
- A bigger sort
- Dynamic programming
- More coins