Show problems as
Classic problem #860EasyArrayGreedy

Lemonade Change

Real-world version: Locker Kiosk Change
Tracked in this browser only
Read Lemonade Change on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A left-luggage kiosk rents one locker per traveller at a flat 5 credits. Travellers reach the counter in the order given by tokens, and tokens[i] is the single token the i-th traveller hands over: worth 5, 10 or 20 credits.

The kiosk opens with an empty till. Whenever a traveller pays more than 5 credits, the kiosk must hand back the difference using whole tokens it already holds, and the only tokens it holds are the ones earlier travellers paid with. A traveller paying 10 needs 5 credits back, and a traveller paying 20 needs 15 credits back.

Return true if every traveller can be given exact change in this order, and false if some traveller cannot.

Examples

Example 1

Input
tokens = [5,5,5,5,10,20,10,10]
Output
true

The fifth traveller is handed one 5 back. The sixth is handed a 10 and a 5, which is the 15 credits owed. The last two are each handed one 5 back, so nobody is short.

Example 2

Input
tokens = [5,5,20,5,10]
Output
false

When the third traveller pays 20, the till holds only two 5 tokens, which is 10 credits, so the 15 credits owed cannot be handed back.

Constraints

  • 1 <= tokens.length <= 10^5
  • tokens[i] is either 5, 10, or 20.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def can_serve_all(tokens: list[int]) -> bool:
Java
public boolean canServeAll(int[] tokens)