Introduction
Lemonade Change is a classic Greedy simulation problem.
You are selling lemonade for:
$5 per lemonadeCustomers pay using:
$5, $10, or $20Goal:
Return correct change to every customer.
Initially:
You have no money.Example
Input
bills = [5,5,5,10,20]
Output
true Explanation
Customer 1 → pays $5Customer 2 → pays $5 Customer 3 → pays $5 Customer 4 → pays $10 Give back $5
Customer 5 → pays $20 Give back $15
All customers receive correct change.
Key Observation
Whenever possible:
Use one $10 bill and one $5 bill instead of three $5 bills.This preserves more small bills for future transactions.
Algorithm
- Maintain count of $5 bills.
- Maintain count of $10 bills.
- Process customers one by one.
- If bill is $5, keep it.
- If bill is $10, give one $5 back.
- If bill is $20:
- Prefer $10 + $5 change.
- Otherwise use three $5 bills.
- If change cannot be given, return false.
Dry Run
Input
[5,5,5,10,20] Customer 1
Receive $5five = 1Customer 2
Receive $5
five = 2Customer 3
Receive $5
five = 3Customer 4
Receive $10
Give $5
five = 2
ten = 1Customer 5
Receive $20
Give $10 + $5
five = 1
ten = 0Answer
trueApproach : Greedy
Always try to give larger bills first when returning change.
Using one $10 and one $5 is better than using three $5 bills because it preserves smaller denominations.