A cashier has to give change with as few coins as possible. The cashier doesn't check every option. The cashier just takes the biggest coin that still fits (not more than the change still to give), then repeats until nothing is left. It's quick, and with everyday coins it usually does give the fewest.
Working like the cashier is called greedy: always take the choice that looks best right now, without thinking about the steps after it. In the cashier example, the choice that looks best right now is the biggest coin that still fits. It's simple and fast, but the end result isn't always the best one.
Take the biggest coin that still fits
These are the steps when you have to pay 67 cents with the coins [25, 10, 5, 1]:
| Step | Left to pay | Biggest coin that fits | Left after |
|---|---|---|---|
| 1 | 67 | 25 | 42 |
| 2 | 42 | 25 | 17 |
| 3 | 17 | 10 | 7 |
| 4 | 7 | 5 | 2 |
| 5 | 2 | 1 | 1 |
| 6 | 1 | 1 | 0 |
That's 6 coins. Each step only looks at what's left right now and takes the biggest coin that isn't more than that.
Here is the code, as a function named greedyCoins. amount is what you have to pay, and coins is the coin set (the kinds of coins you have):
function greedyCoins(amount, coins) {
const result = [];
for (const coin of coins) {
while (amount >= coin) {
result.push(coin);
amount -= coin;
}
}
return result;
}
console.log(greedyCoins(67, [25, 10, 5, 1])); // [25, 25, 10, 5, 1, 1]
console.log(greedyCoins(67, [25, 10, 5, 1]).length); // 6
coinsis sorted biggest first, sofor...oftries the biggest coin first.while (amount >= coin)takes the same coin again and again for as long as it fits. Use>=: a 5 coin still fits when 5 is left.- Each time a coin is taken, it goes into
result, andamountdrops by its value. - If
amountis 0, no coin is taken, and the result is an empty array.
In the exercise, you only need the number of coins. For that, replace result.push(coin) with a counter that starts at 0 (coinCount++), then return the counter. Another example: 41 cents becomes 25 + 10 + 5 + 1, four coins.
When greedy loses
Guess first: if the only coins are 4, 3 and 1, and you have to pay 6, how many coins does greedy use? Is there a way with fewer?
With the coins [4, 3, 1] and an amount of 6, greedy takes the 4 first because it's the biggest. That leaves 2, which is paid with 1 + 1. Three coins in all. Yet 3 + 3 is only 2 coins. Greedy loses.
The problem is that the 4 looks best at the first step. But once the 4 is taken, only 2 is left, so the better answer (3 + 3) is no longer possible. Greedy never goes back to change a choice.
For the coins [25, 10, 5, 1], greedy always finds the fewest coins. A coin set where greedy is always right is called canonical. For any coin set, use dynamic programming (DP) from the Memoization & Dynamic Programming lesson, like minCoins there. DP calculates the best answer for every smaller amount first, from 1 up to amount. So DP is slower, but always right.
Some problems have a greedy rule that is proven always right. One is planning a single room. There are five events: 9 to 12, 10 to 11, 11 to 13, 12 to 14 and 13 to 15 o'clock. Choose as many events as possible whose times do not overlap. The greedy rule: sort the events by their end time, then take each event that starts when or after the last chosen event ends. The result is 10 to 11, 11 to 13 and 13 to 15: three events, the most possible. Another rule, taking the event that starts first, gets only two events: 9 to 12, then 12 to 14. The end-time rule is always right, because the event that ends first leaves the most time for the events after it. Dijkstra, in the Dijkstra: Shortest Path lesson, is also a greedy algorithm proven right (always take the nearest town), as long as no weight is negative. So are Prim and Kruskal, in the next lesson, Minimum Spanning Tree.
⚠️ Coins in the wrong order, and an if that should be a while
- Coins listed smallest first. With
[1, 5, 10, 25], the 1 coin is taken again and again until nothing is left. Greedy needs the biggest coin at the front. ifinstead ofwhile.iftakes only one coin of each kind, yet 67 needs two 25 coins.- Returning the list of coins. When the task asks how many coins, as the exercise does, return a number (
result.lengthor a counter), not an array.
💡 How to check greedy. Before you trust greedy, try a few small amounts and compare them with the DP answer or a count by hand. One case where greedy loses is enough to show greedy can't be used for that task.
TL;DR: Greedy always takes the best choice right now and never goes back to change it. For change: sort the coins biggest first, take each coin with while (amount >= coin) while it still fits in amount (what's left to pay), lower what's left, and count the coins. With [25, 10, 5, 1], greedy always gives the fewest coins (41 becomes 4 coins). With [4, 3, 1] to pay 6, greedy gets 3 coins, while 3 + 3 is only 2 coins. When greedy isn't proven right, use DP (dynamic programming).
⚡ Take the biggest coin that still fits
Write:
function greedyCoins(amount, coins) {
const result = [];
for (const coin of coins) {
while (amount >= coin) {
result.push(coin);
amount -= coin;
}
}
return result;
}
console.log(greedyCoins(67, [25, 10, 5, 1]).length); // 6
Meaning: greedyCoins pays amount the greedy way: always take the biggest coin that still fits (not more than what's left). coins must already be sorted biggest first. while, not if, so the same coin can be taken again and again, and >= so a 5 coin still fits when 5 is left.
⚡ When greedy loses
Guess first: the only coins are 4, 3 and 1, and you have to pay 6. How many coins does greedy use?
3 coins: the 4 first because it's the biggest, then the 2 left is paid with 1 + 1. Yet 3 + 3 is only 2 coins.
Meaning: Greedy always takes the choice that looks best right now and never goes back to change it. The 4 looks best at the first step, but once the 4 is taken, the answer 3 + 3 is no longer possible.
⚡ Greedy or DP?
Meaning: For the coins [25, 10, 5, 1], greedy always finds the fewest coins. For any coin set, use DP (dynamic programming), which calculates the best answer for every smaller amount first: slower, but sure to find the best.