Lemonade Change
Greedy change-making with $5 and $10 bills
Each lemonade costs $5. A $5 bill gives you change flexibility for any future customer, while a $10 bill can only help make change for a $20 bill. Therefore, the greedy rule is: when a customer gives $10, you must give one $5; when a customer gives $20 (requiring $15 change), always prefer giving one $10 and one $5 over three $5 bills. Preserving valuable $5 bills for future customers is strictly optimal.
Details
Animated on: bills = [5, 5, 5, 10, 20] — determine if you can provide every customer with correct change.
Problem:Lemonade ChangeEasy
Greedy change-making with $5 and $10 bills
step 1 / 9
Start with five=0, ten=0. Customer 0 pays with a $5 bill. No change required.
- i=0· arr[0] = 5
1FUNCTION lemonadeChange(bills):2 five = 0, ten = 03 FOR each bill in bills:4 IF bill is 5: add one to five5 ELSE IF bill is 10: if no five available RETURN false, else five down one and ten up one6 ELSE: (bill is 20, needs $15 change)7 IF ten > 0 and five > 0: give one ten and one five8 ELSE IF five >= 3: give three fives9 ELSE: RETURN false10 RETURN true
← / → step · space play · Home restart
Every step in words
Show all 9 steps
- Start with five=0, ten=0. Customer 0 pays with a $5 bill. No change required.
- Collect $5: five count increases to 1, ten=0. Customer satisfied.
- Customer 1 pays with $5. No change needed: five becomes 2, ten=0.
- Customer 2 pays with $5. No change needed: five becomes 3, ten=0.
- Customer 3 pays with $10. Needs $5 change. We have five=3 > 0, so give one $5 bill.
- Hand over one $5 in change. Bank now holds five=2, ten=1.
- Customer 4 pays with $20 (requires $15 change). Check greedy option: one $10 + one $5 bill.
- Greedily give one $10 and one $5 ($15 total), preserving one remaining $5 bill. Updated bank: ten=0, five=1.
- All customers served with correct change. Return true.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.