◀ THE GRIND — GREEDY

Lemonade Change

The drill: A lemonade stand charges $5 and starts with an empty till. Customers pay with $5, $10, or $20 bills in a fixed order — decide whether every one of them can get correct change from bills collected so far.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A line of customers pays for five-dollar lemonades one at a time, each handing over a five, a ten, or a twenty. Every purchase needs exact change back, drawn only from bills already collected earlier in the line.

The till starts empty, and bills accumulate strictly in the order customers pay — there's no reordering the line or peeking ahead. The moment any customer can't get correct change, the whole line of service fails.

The result is a single verdict: whether every customer in the given order walks away with correct change, using only bills that arrived before them.

EX 01
bills = [5, 5, 5, 5, 10, 20, 20]
false
TWO TWENTIES STRAND A LONE FIVE
EX 02
bills = [5, 5, 10, 20]
true
TEN-PLUS-FIVE CHANGE WORKS
EX 03
bills = [10, 5, 20]
false
OPENS WITH A TEN — NO CHANGE ON HAND
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Checking every possible way to hand out change explores a branching tree of choices at each $20 — but two of the bills you could hand back are worth exchanging for. Which one is more valuable to keep on hand?

HINT 2 THE STRUCTURE

A $5 bill can cover change for a $10 OR a $20. A $10 bill can only ever cover change for a $20. Spending the less flexible bill first is never a mistake.

HINT 3 ONE STEP FROM THE ANSWER

Track running counts of fives and tens only — tens never help elsewhere. For a $20, use one ten plus one five if you have both; otherwise fall back to three fives; otherwise the till has failed.

COACH'S BOARD — THE PATTERN, STEP BY STEP
KEEP THE FIVES SCARCEPATTERN · GREEDYbills = [5, 5, 5, 10, 10, 20, 5, 20]
5
5
5
10
10
20
5
20
TILL — FIVES · TENS
fives0
tens0
STEP 1

Bills arrive in order 5, 5, 5, 10, 10, 20, 5, 20. The till starts with zero fives and zero tens.

STEP 1 / 10 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/lemonade-change.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        five = ten = 0
        for bill in bills:
            if bill == 5:
                five += 1
            elif bill == 10:
                if five == 0:
                    return False
                five -= 1
                ten += 1
            else:
                if ten > 0 and five > 0:
                    ten -= 1
                    five -= 1
                elif five >= 3:
                    five -= 3
                else:
                    return False
        return True
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 20 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED