Lemonade Change - Problem

At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill.

You must provide the correct change to each customer so that the net transaction is that the customer pays $5. Note that you do not have any change in hand at first.

Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.

Input & Output

Example 1 — Mixed Bills
$ Input: bills = [5,5,5,10,20]
Output: true
💡 Note: Customer 1-3: pay $5, no change needed. Customer 4: pays $10, give $5 change. Customer 5: pays $20, give $10+$5 change.
Example 2 — Cannot Make Change
$ Input: bills = [5,5,10,10,20]
Output: false
💡 Note: For the last customer paying $20, we need $15 change but only have $10+$10+$5 available. We cannot make exactly $15.
Example 3 — All Same Bills
$ Input: bills = [5,5,5,5]
Output: true
💡 Note: All customers pay exact amount ($5), so no change is needed.

Constraints

  • 1 ≤ bills.length ≤ 105
  • bills[i] is either 5, 10, or 20

Visualization

Tap to expand
Lemonade Change: Transaction FlowCustomer Queue$5$5$10$20[5,5,10,20]🍋 Lemonade StandPrice: $5 eachMake change greedilyResulttrueTransaction Details:$5 → No change needed$10 → Give $5 change$20 → Give $15 change ($10 + $5)
Understanding the Visualization
1
Input
Queue of customers with different bill denominations
2
Process
Make change using greedy strategy for each customer
3
Output
Return true if all customers can be served, false otherwise
Key Takeaway
🎯 Key Insight: Greedy strategy works because using larger denominations preserves maximum flexibility for future transactions
Asked in
Google 12 Amazon 8 Microsoft 6 Facebook 4
187.4K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen