Lemonade Change - Problem
You're running a bustling lemonade stand! ๐ Each cup of delicious lemonade costs exactly
The tricky part? You start with no money in your cash register! This means you can only make change using the bills you've received from previous customers.
Your task: Given an array
Example: If a customer pays with a
$5, and customers are lining up to buy from you. Here's the challenge: customers pay with $5, $10, or $20 bills, and you need to give them the correct change so they effectively pay exactly $5.The tricky part? You start with no money in your cash register! This means you can only make change using the bills you've received from previous customers.
Your task: Given an array
bills where each element represents the bill amount a customer pays (in order), determine if you can successfully provide correct change to every single customer. Return true if possible, false otherwise.Example: If a customer pays with a
$10 bill, you need to give them $5 change. If a customer pays with a $20 bill, you need to give them $15 change (preferably one $10 and one $5). Input & Output
example_1.py โ Basic Success Case
$
Input:
[5,5,5,10,20]
โบ
Output:
true
๐ก Note:
Customer 1-3 pay with $5 (no change needed). Customer 4 pays $10, we give $5 change. Customer 5 pays $20, we give $15 change ($10 + $5). We can handle all customers successfully.
example_2.py โ Early Failure
$
Input:
[5,5,10,10,20]
โบ
Output:
false
๐ก Note:
After the first 4 customers, we have zero $5 bills and two $10 bills. When customer 5 pays $20, we need $15 change but can't make it with two $10 bills. We need at least one $5 bill.
example_3.py โ Edge Case
$
Input:
[5,5,5,5,20,20,20,20,20]
โบ
Output:
false
๐ก Note:
We start with four $5 bills. First $20 customer takes 3 of them (leaving 1). Second $20 customer would need 3 more $5 bills but we only have 1 remaining.
Constraints
- 1 โค bills.length โค 105
- bills[i] is either 5, 10, or 20
- All customers must be served in the order they appear in the array
Visualization
Tap to expand
Understanding the Visualization
1
Collect $5 bills
These are pure profit - no change needed, but crucial for future transactions
2
Handle $10 bills
Easy trade: give one $5 as change, gain one $10 (which helps with $20s later)
3
Strategic $20 handling
Always prefer giving $10+$5 change over three $5s to preserve smaller denominations
4
Early termination
Return false immediately when you can't make change - no point continuing
Key Takeaway
๐ฏ Key Insight: This is a perfect greedy problem! Always prioritize preserving smaller denominations ($5 bills) since they're needed for all change-making scenarios, while larger bills ($10, $20) have limited utility.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code