progress

~/problems / Greedy

Lemonade Change

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~12 min

A ferry ticket costs 5. Each customer in the queue buys one ticket with a single 5, 10 or 20 note. Your till starts empty, and you can only give change from notes earlier customers paid.

Write can_give_change(bills: list[int]) -> bool: True if every customer gets correct change, in queue order.

can_give_change([5, 5, 5, 10, 20])    # True
can_give_change([5, 5, 10, 10, 20])   # False  the last customer needs 15 back, but the till holds 10 + 10
can_give_change([10])                 # False  nothing in the till yet
can_give_change([5, 5, 10, 20])       # True   pay the 20 back with 10 + 5

Up to 10^5 customers.

⭐ Bonus: a speed test with 100,000 customers earns a star in O(n) time.

Show hint

only 5s and 10s go back out. When a 20 arrives and there are two ways to give 15, which one leaves you better prepared?

Topic: Greedy with sorting. Sort, then take the locally best choice; prove it with an exchange argument.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc