Greedy Algorithms · Simulation · Bills

Lemonade Change Visualizer

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

Search every way to make changeA 20 can be paid as 10+5 or as 5+5+5. Trying both branches, and every later customer, explores combinations the line never needs.
Spend the 10 firstA 20 is never useful as change, so only the counts of 5s and 10s matter. Giving away a 10 and a 5 on a 20 leaves more 5s for later 10s. Three 5s are the backup. If neither set is in the register, the line fails at this customer.

Interactive visualization

Step through the greedy choice

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.

five = 0, ten = 0
for each bill in order:
if bill == 5: five += 1
if bill == 10 and five > 0: five -= 1, ten += 1
if bill == 10 and five == 0: return false
if bill == 20 and ten > 0 and five > 0: spend 10 and 5
else if five >= 3: five -= 3
else return false
return true
Step 0 Answer —

Complexity

PieceCostWhy
TimeO(n)Each customer is handled once.
SpaceO(1)Two counters, for 5s and 10s.
Greedy choice10 + 5 before three 5sA 5 is the only bill that can make change for a later 10.

Implementation

def lemonade_change(bills): five = ten = 0 for bill in bills: if bill == 5: five += 1 elif bill == 10: if five == 0: return False five -= 1 ten += 1 elif ten > 0 and five > 0: ten -= 1 five -= 1 elif five >= 3: five -= 3 else: return False return True