Emmanuel Akinfulubi

JavaScriptFunction

Coin change: break an amount into coins in JavaScript

Intermediate · 4 min read

Every cash register and vending machine has to solve this problem: give someone 46 cents using as few coins as possible. With coins of 25, 10, 5, 2 and 1, the answer is 25, 10, 10, 1. The same idea shows up when an ATM chooses notes, or when a shop splits a payment into packs of different sizes.

In this tutorial you will write amountToCoins(amount, coins) using a greedy method, which means always taking the biggest coin that fits. Then you will find a set of coins where greedy gets stuck, and see the method that always finds the best answer. You need to know for and while loops and what an array is.

The greedy idea

Greedy is what most people do in their head. To make 46:

  1. The biggest coin that fits is 25. Take it, 21 left.
  2. The biggest that fits now is 10. Take it, 11 left.
  3. 10 again, 1 left.
  4. Then 1. Done.

At each step you make the choice that looks best right now, without planning ahead. That is why it is called greedy.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

14 Break an amount into coins

fair

amountToCoins(46, [25, 10, 5, 2, 1]) should give 25, 10, 10, 1. Then find the coin set where this approach fails.

Stuck? Three hints, smallest first
  1. 1. Greedy: take the largest coin that fits, repeatedly.
  2. 2. That is only guaranteed optimal for some coin systems, including ordinary currency.
  3. 3. Sort the coins descending first, so the caller does not have to.

Step 1: sort the coins, biggest first

Greedy needs to try the biggest coin first. The caller might pass the coins in any order, so sort a copy from biggest to smallest. (a, b) => b - a is the compare function for "largest first", and [...coins] copies the array so the caller's list stays as it was:

Step 1

const coins = [1, 25, 2, 10, 5];
const sorted = [...coins].sort((a, b) => b - a);
console.log(sorted); // [ 25, 10, 5, 2, 1 ]
console.log(coins);  // [ 1, 25, 2, 10, 5 ]

Step 2: take each coin while it fits

For each coin, a while loop keeps taking it as long as it fits in what is left:

Step 2

function greedySketch(amount, coins) {
  const sorted = [...coins].sort((a, b) => b - a);
  const out = [];
  let left = amount;
  for (const coin of sorted) {
    while (left >= coin) { out.push(coin); left -= coin; }
  }
  return out;
}
console.log(greedySketch(46, [25, 10, 5, 2, 1])); // [ 25, 10, 10, 1 ]

left -= coin means left = left - coin. The while takes 10 twice, then moves on once 10 no longer fits.

That matches the exercise. Now the second half of the task: find coins where this fails.

Step 3: where greedy gets stuck

Try coins of 25, 10 and 4, and an amount of 41:

Step 3

console.log(greedySketch(41, [25, 10, 4])); // [ 25, 10, 4 ]

25 + 10 + 4 is only 39. Greedy took 25, then 10, then 4, and was left with 2. No coin is that small, so it stopped, and the coins it returned don't add up to 41. Worse, nothing in the result says so.

Yet 41 can be made: 25 + 4 + 4 + 4 + 4. Greedy missed it because taking the 10 early looked good but left an amount the 4s couldn't finish.

Step 4: report failure honestly

The answer checks what is left at the end. If it is 0, it returns the coins. If not, it returns an object that says what it managed and what is missing. It also refuses amounts that are negative or not whole:

Step 4

function amountToCoins(amount, coins) {
  if (!Number.isInteger(amount) || amount < 0) return null;
  const sorted = [...coins].sort((a, b) => b - a);
  const out = [];
  let left = amount;
  for (const coin of sorted) {
    while (left >= coin) { out.push(coin); left -= coin; }
  }
  return left === 0 ? out : { incomplete: out, remaining: left };
}
console.log(amountToCoins(46, [25, 10, 5, 2, 1])); // [ 25, 10, 10, 1 ]
console.log(amountToCoins(41, [25, 10, 4]));       // { incomplete: [ 25, 10, 4 ], remaining: 2 }
console.log(amountToCoins(-5, [25, 10, 5, 2, 1])); // null

Now a caller can tell success from failure: success is an array, failure is not.

Step 5: the method that always works

To always find the fewest coins, you can work out the best answer for every amount from 0 up to the target, reusing the smaller answers. The best way to make 41 is "the best way to make 41 - coin, plus that coin", for whichever coin gives the shortest list. This technique is called dynamic programming.

Step 5

function fewestCoins(amount, coins) {
  const best = Array(amount + 1).fill(null);
  best[0] = [];
  for (let target = 1; target <= amount; target++) {
    for (const coin of coins) {
      if (coin > target || best[target - coin] === null) continue;
      const candidate = [...best[target - coin], coin];
      if (best[target] === null || candidate.length < best[target].length) best[target] = candidate;
    }
  }
  return best[amount];
}
console.log(fewestCoins(41, [25, 10, 4])); // [ 4, 4, 4, 4, 25 ]

best[t] holds the shortest list of coins that makes t, or null if t can't be made. best[0] is an empty list, because 0 needs no coins. Each target tries every coin and keeps the shortest result.

Greedy is still useful. For ordinary currency coins, it always gives the best answer, and the full solution checks that it agrees with fewestCoins for every amount from 1 to 60. Greedy just isn't safe for every possible set of coins.

The full solution

The panel has amountToCoins and fewestCoins. It prints the answer for 46, checks the coins add up, then shows greedy getting stuck on 41 with coins of 25, 10 and 4, and the five-coin answer that does work. Press Run to see them.

The answer

// Greedy: always take the biggest coin that fits.
function amountToCoins(amount, coins) {
  if (!Number.isInteger(amount) || amount < 0) return null;
  const sorted = [...coins].sort((a, b) => b - a);      // descending, and a copy
  const out = [];
  let left = amount;
  for (const coin of sorted) {
    while (left >= coin) { out.push(coin); left -= coin; }
  }
  return left === 0 ? out : { incomplete: out, remaining: left };
}

// The genuinely optimal answer, by dynamic programming.
function fewestCoins(amount, coins) {
  const best = Array(amount + 1).fill(null);
  best[0] = [];
  for (let target = 1; target <= amount; target++) {
    for (const coin of coins) {
      if (coin > target || best[target - coin] === null) continue;
      const candidate = [...best[target - coin], coin];
      if (best[target] === null || candidate.length < best[target].length) best[target] = candidate;
    }
  }
  return best[amount];
}

const normal = [25, 10, 5, 2, 1];
console.log('amountToCoins(46, [25,10,5,2,1]) =', amountToCoins(46, normal).join(', '));
console.log("the expected value               =  25, 10, 10, 1");
console.log('sum check:', amountToCoins(46, normal).reduce((a, b) => a + b, 0));
console.log('--- where greedy fails ---');
const awkward = [25, 10, 4];
console.log('greedy for 41 with [25,10,4]:', JSON.stringify(amountToCoins(41, awkward)));
console.log('<- it took 25, 10 and 4, then had 2 left and no coin small enough');
console.log('optimal for 41              :', fewestCoins(41, awkward).join(' + '), '=', fewestCoins(41, awkward).reduce((a, b) => a + b, 0));

Output


      
18 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 18 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

18 checks

test("the example in the question", amountToCoins(46, normal), [25, 10, 10, 1]);
test('and it adds up', amountToCoins(46, normal).reduce((a, b) => a + b, 0), 46);
test('an exact coin gives one coin', amountToCoins(25, normal), [25]);
test('zero gives no coins', amountToCoins(0, normal), []);
test('one gives the smallest coin', amountToCoins(1, normal), [1]);
test('coins come out largest first', amountToCoins(46, normal).every((c, i, a) => i === 0 || c <= a[i - 1]), true);
test('an unsorted coin list still works', amountToCoins(46, [1, 25, 2, 10, 5]), [25, 10, 10, 1]);
test('the caller\u2019s list is not reordered', (() => { const c = [1, 25, 5]; amountToCoins(30, c); return c; })(), [1, 25, 5]);
test('a negative amount is refused', amountToCoins(-5, normal), null);
test('a decimal amount is refused', amountToCoins(5.5, normal), null);
test('greedy fails on an awkward coin set', Array.isArray(amountToCoins(41, awkward)), false);
test('and reports what it could not make', amountToCoins(41, awkward).remaining, 2);
test('the optimal version does make 41', fewestCoins(41, awkward).reduce((a, b) => a + b, 0), 41);
test('using five coins', fewestCoins(41, awkward).length, 5);
test('namely 25 and four 4s', fewestCoins(41, awkward).slice().sort((a, b) => a - b), [4, 4, 4, 4, 25]);
test('which greedy never found', Array.isArray(amountToCoins(41, awkward)), false);
test('on a normal coin set the two agree', fewestCoins(46, normal).length, amountToCoins(46, normal).length);
test('and for many amounts', Array.from({ length: 60 }, (_, i) => i + 1).every((n) => fewestCoins(n, normal).length === amountToCoins(n, normal).length), true);

Greedy is the obvious approach and it is not always right. With coins [25, 10, 4] and an amount of 41, greedy takes 25, then 10, and is left needing 6 — which it cannot make. The assertions show it returning an incomplete result with 6 remaining, while the optimal answer is 4 + 4 + 4 + 25. This is why the function reports failure rather than silently returning coins that do not add up.

Greedy is optimal for what are called canonical coin systems, which includes every real currency — the last assertion checks the two agree for every amount from 1 to 60 with ordinary coins. So in practice greedy is fine; the point is knowing the condition rather than assuming it.

fewestCoins builds up the best answer for every amount from 0 to the target, reusing the smaller results. That is dynamic programming, and it is the standard fix when a greedy choice can paint you into a corner.

Common mistakes

  • Assuming the coins arrive sorted. If 1 comes first, greedy takes 46 ones. Sort a copy, biggest first.
  • Returning coins that don't add up. Always check what is left. A wrong answer that looks like a right one is the worst kind.
  • Trusting greedy for any coins. It is only guaranteed for some coin sets, such as real currency.

Try it yourself

  1. Run amountToCoins(30, [25, 10]) and fewestCoins(30, [25, 10]). Explain the difference.
  2. Change amountToCoins to return how many of each coin, like { 25: 1, 10: 2, 1: 1 }.
  3. Find another amount below 41 where greedy fails with coins of 25, 10 and 4.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.