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 - Greedy Strategy INPUT LEMONADE $5 each Customer Queue (bills): $5 $5 $5 $10 $20 [0] [1] [2] [3] [4] Initial Cash Register: $5: 0 | $10: 0 | $20: 0 Goal: Give correct change to every customer bills = [5, 5, 5, 10, 20] ALGORITHM STEPS 1 Track Bills Count $5 and $10 bills only 2 Process Each Customer $5: keep, $10/$20: give change 3 Greedy Change For $20: prefer $10+$5 over 3x$5 4 Return Result True if all served, else false Simulation: Bill Change $5s $10s OK $5 $0 1 0 OK $5 $0 2 0 OK $5 $0 3 0 OK $10 $5 2 1 OK $20 $10+$5 1 0 OK FINAL RESULT OK All Customers Served! Output: true Can serve everyone Final Cash Register: $5 x1 $10 x0 $20 x1 Every customer received correct change successfully Key Insight: The greedy approach prioritizes using $10 bills for change when possible. For $20 payments, giving $10+$5 is better than 3x$5 because $5 bills are more versatile - they can make change for both $10 and $20 bills, while $10 bills can only help with $20 payments. TutorialsPoint - Lemonade Change | Greedy Strategy
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