Lemonade Change
Each lemonade costs $5 and customers pay with $5, $10, or $20 bills. Serving them in order, return whether you can give correct change to everyone.
Open on LeetCode ↗Intuition
There is exactly one decision in this problem, and it is where people lose it: giving $15 back for a $20. Three fives works and feels natural. It is wrong. A ten can only ever serve a twenty, while a five serves both tens and twenties — so burning three flexible notes to save a rigid one strands you later. Spend the ten. Everything else here is forced, and a twenty is never change at all, so two counters cover the whole problem.
Approach
Notice that twenties are dead weight
Change is only ever given in fives and tens, so a $20 bill enters the till and never leaves it. Tracking it would be wasted state; two counters describe everything that matters.
Handle the forced cases
A $5 needs no change — take it and the five count rises. A $10 needs exactly $5 back, and the only way to make that is one five, so there is no choice to make: if no five is available, fail immediately.
Make the greedy choice on $20
A $20 needs $15 back: a ten plus a five, or three fives. Always prefer the ten. The exchange argument: any solution paying with three fives can be rewritten to use the ten instead without getting worse, since the ten has no other use. Hand out the specialised note, hoard the versatile one. Try it on [5,5,5,10,20] — pay the twenty with three fives and the next ten has nothing to draw on. One pass, O(n) time and O(1) space.
Solution & live demo
Edge cases
The till is empty, so change is impossible and the answer is false on the first step.
No change is ever needed; the answer is true.
The greedy rule prevents this; doing it can strand a later $20 that only a ten could have helped serve.
Handled naturally — the counters simply reach zero at the end.