What is Lemonade Change
Each lemonade costs 5. Customers stand in a line and each pays with one bill of 5, 10, or 20. You must give the correct change immediately, using only bills you have already received. Return true when every customer can be served in order.
Change rules: a 5 needs nothing, a 10 needs one 5 back, and a 20 needs 15 back. For a 20, prefer handing over one 10 and one 5. If that pair is unavailable, hand over three 5s.
Example 1. Three 5s, then a 10, then a 20. The 20 is paid with the 10 plus one 5.
Input: 5 5 5 10 20 Output: true
Example 2. The second 10 spends the last 5. The 20 then has two 10s and no 5, so 15 cannot be made.
Input: 5 5 10 10 20 Output: false
Approach
Interactive visualization
The walk starts on the first pseudocode line. Next and Play move one step at a time, and the highlighted line is the line that just ran.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each customer is handled once. |
| Space | O(1) | Two counters, for 5s and 10s. |
| Greedy choice | 10 + 5 before three 5s | A 5 is the only bill that can make change for a later 10. |
Implementation