Emmanuel Akinfulubi

JavaScriptBasic

Give change with the fewest notes (greedy) in JavaScript

Intermediate · 4 min read

A shop till, a vending machine and a cash-withdrawal screen all solve the same puzzle: pay out an amount using as few notes as possible. For ₦3,780 that means three ₦1,000 notes, one ₦500, one ₦200, one ₦50, one ₦20 and one ₦10. The usual way to work it out is called a greedy algorithm, and it's a great first look at how algorithms are designed.

In this tutorial you will write a function called change that breaks an amount into naira notes, reports any part that can't be paid in notes, and works in kobo to avoid rounding errors. At the end you'll see a set of notes where the greedy approach stops giving the best answer. You need to know what arrays, loops and functions are.

What "greedy" means

A greedy algorithm makes the choice that looks best right now, and never goes back. For change, that means: take as many of the biggest note as fit, then as many of the next biggest, and so on down to the smallest.

To give ₦3,780: three ₦1,000 notes fit (₦3,000), leaving ₦780. One ₦500 fits, leaving ₦280. One ₦200, leaving ₦80. No ₦100. One ₦50, leaving ₦30. One ₦20, one ₦10, done.

Why work in kobo

There are 100 kobo in a naira. Computers store decimal numbers like 0.1 slightly inaccurately, so sums of money in naira with decimals can come out a tiny bit wrong:

JavaScript

console.log(0.1 + 0.2); // 0.30000000000000004

Whole numbers don't have this problem. So the code holds every amount in kobo, as a whole number: ₦3,780 is 378000 kobo and the ₦1,000 note is 100000.

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

121 Change in naira notes

fair

Give change for ₦3,780 using the fewest notes: ₦1,000, ₦500, ₦200, ₦100, ₦50, ₦20, ₦10 and ₦5. Work in kobo, report what cannot be paid in notes, and then show a set of denominations where taking the biggest note first is not the fewest.

Stuck? Three hints, smallest first
  1. 1. Walk the denominations from largest to smallest, taking as many of each as fit.
  2. 2. Math.floor(left / note) is the count; subtract before moving on.
  3. 3. Whatever is left when the smallest note is done is the part you cannot pay.

Step 1: how many of one note fit

Step 1

let left = 378000;
const note = 100000;
const count = Math.floor(left / note);
left -= count * note;
console.log(count, left); // 3 78000

Math.floor(left / note) divides and drops the fraction, so it's the number of whole notes that fit. left -= count * note takes their value away. -= is short for left = left - count * note.

Step 2: loop over every note

Step 2

const NOTES = [100000, 50000, 20000, 10000, 5000, 2000, 1000, 500];
function change(kobo, notes = NOTES) {
  let left = kobo;
  const given = [];
  for (const note of notes) {
    const count = Math.floor(left / note);
    if (count > 0) given.push([note, count]);
    left -= count * note;
  }
  return { given, unpaid: left };
}
const paid = change(378000);
console.log(paid.given); // [ [ 100000, 3 ], [ 50000, 1 ], [ 20000, 1 ], [ 5000, 1 ], [ 2000, 1 ], [ 1000, 1 ] ]
console.log(paid.unpaid); // 0

NOTES is sorted from the biggest note to the smallest, which is what makes this greedy. For each note, the loop works out the count, records [note, count] if it's more than zero, and subtracts.

The ₦100 note (10000) isn't in the result, because after the ₦200 only ₦80 was left. And a note bigger than what's left is skipped without fuss: its count is just 0.

Step 3: what can't be paid

Step 3

const NOTES = [100000, 50000, 20000, 10000, 5000, 2000, 1000, 500];
function change(kobo, notes = NOTES) {
  let left = kobo;
  const given = [];
  for (const note of notes) {
    const count = Math.floor(left / note);
    if (count > 0) given.push([note, count]);
    left -= count * note;
  }
  return { given, unpaid: left };
}
console.log(change(378050).unpaid); // 50

₦3,780.50 has 50 kobo that no note can cover, since the smallest note is ₦5. The function doesn't hide it: unpaid says exactly how much is still owed. A till that quietly drops a few kobo on every sale ends up short at the end of the day.

Step 4: check the answer adds up

Two small helpers make the result easy to test:

Step 4

const totalOf = (given) => given.reduce((sum, [note, count]) => sum + note * count, 0);
const noteCount = (given) => given.reduce((sum, [, count]) => sum + count, 0);
const given = [[100000, 3], [50000, 1], [20000, 1], [5000, 1], [2000, 1], [1000, 1]];
console.log(totalOf(given));   // 378000
console.log(noteCount(given)); // 8

reduce keeps a running total. [note, count] unpacks each pair, and [, count] skips the first item because only the count is needed. The notes add back to exactly ₦3,780, and there are eight of them.

Step 5: when greedy isn't the best

Greedy gives the fewest notes for the naira notes. It doesn't for every set. Imagine notes of 400, 300 and 100, and an amount of 600:

Step 5

function change(kobo, notes) {
  let left = kobo;
  const given = [];
  for (const note of notes) {
    const count = Math.floor(left / note);
    if (count > 0) given.push([note, count]);
    left -= count * note;
  }
  return { given, unpaid: left };
}
console.log(change(600, [400, 300, 100]).given); // [ [ 400, 1 ], [ 100, 2 ] ]

Greedy takes the 400 first, then needs two 100s: three notes. Two 300s would have done it in two. Grabbing the biggest note first locked it out of the better answer.

So greedy is the right choice for the naira notes, but it isn't a rule for every set. Finding the true minimum for any set of notes needs a different method, called dynamic programming. It's worth writing a comment next to NOTES saying the greedy approach depends on these values, so nobody adds an unusual note without checking.

The full solution

The answer panel has change, totalOf and noteCount, and prints the breakdown for ₦3,780 and the 50 kobo left over from ₦3,780.50. The checks cover the eight notes, the exact breakdown, the total adding back, the unpaid part, zero, a note larger than the amount, and the 400/300/100 case. Press Run to see the output.

The answer

const NOTES = [100000, 50000, 20000, 10000, 5000, 2000, 1000, 500];   // kobo
function change(kobo, notes = NOTES) {
  let left = kobo;
  const given = [];
  for (const note of notes) {
    const count = Math.floor(left / note);
    if (count > 0) given.push([note, count]);
    left -= count * note;
  }
  return { given, unpaid: left };
}
const totalOf = (given) => given.reduce((sum, [note, count]) => sum + note * count, 0);
const noteCount = (given) => given.reduce((sum, [, count]) => sum + count, 0);
const paid = change(378000);
console.log(paid.given.map(([note, count]) => count + ' x ' + note / 100).join(', '));
console.log('50 kobo owing:', change(378050).unpaid);

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('three thousand seven hundred and eighty naira takes eight notes', noteCount(paid.given), 8);
test('and this is the breakdown, in kobo', paid.given, [[100000, 3], [50000, 1], [20000, 1], [5000, 1], [2000, 1], [1000, 1]]);
test('the notes add back to exactly the amount', [totalOf(paid.given), paid.unpaid], [378000, 0]);
test('fifty kobo cannot be paid in notes and is reported, not lost', change(378050).unpaid, 50);
test('while the payable part is still fully covered', totalOf(change(378050).given), 378000);
test('nothing owed needs no notes', change(0), { given: [], unpaid: 0 });
test('a note larger than the amount is skipped, not forced', change(30000).given, [[20000, 1], [10000, 1]]);
test('but biggest-first is not always fewest', noteCount(change(600, [400, 300, 100]).given), 3);
test('because two 300s would have done it', 300 * 2, 600);

Kobo integers throughout, for the reason exercise 63 argues: ₦3,780 held as 3780.00 makes left / note a float division and the remainder a number like 0.00000000004, which is neither zero nor payable. In integer kobo the remainder is exact, so unpaid is trustworthy — and reporting it is the point, because 50 kobo cannot be handed over when the smallest note is ₦5. Dropping it silently is how a till goes out by a few kobo a day.

The last two assertions are the honest caveat. Taking the biggest note first is optimal for the naira ladder, and for any system where each denomination divides the next, but it is not optimal in general: with notes of 400, 300 and 100, greedy pays 600 as 400+100+100 while two 300s would do. Genuinely minimal change is a dynamic-programming problem. Greedy is the right code here because the denominations are known and well behaved — a fact worth writing in a comment, since the day someone adds a ₦300 note the algorithm silently becomes wrong.

Common mistakes

  • Working in naira with decimals. Floating-point leftovers like 0.00000000004 are neither zero nor payable. Use whole kobo.
  • Listing the notes smallest first. Greedy only works from the biggest down; smallest first would pay everything in ₦5 notes.
  • Throwing away the remainder. Return it, so the caller knows something is still owed.

Try it yourself

  1. Print the result as text: '3 x ₦1000, 1 x ₦500, ...'.
  2. Add coins of ₦1 and ₦2 (100 and 200 kobo) to the list and pay ₦3,783.
  3. Write fewestNotes(amount, notes) that tries every combination for small amounts, and check it finds two notes for 600 with [400, 300, 100].

Keep practising

Newsletter

New writing, when it lands.

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