oneby7

Greedy The best choice now

500. Lemonade Change

Easy

You run a lemonade stand, and each cup costs 5. Customers stand in a line and you serve them in order. Customer i buys one cup and pays with a single bill, bills[i], which is a 5, a 10 or a 20. Each customer must get change back, so that they pay exactly 5.

The stand starts with no money at all. You can give change only from the bills that earlier customers paid with, and each customer gets their change before the next one is served.

Return true if you can give every customer the right change, and false otherwise.

Example 1

Input: bills = [5, 5, 5, 10, 20, 10, 5]

Output: true

Explanation: The first three customers pay exactly 5. The fourth gets a 5 back, and the fifth gets a 10 and a 5. The sixth gets the last 5, and the seventh pays exactly.

Example 2

Input: bills = [5, 5, 10, 10, 20]

Output: false

Explanation: When the last customer pays 20, we hold two 10s and no 5. That is 20 in all, but no mix of those bills makes 15.

Example 3

Input: bills = [10, 5]

Output: false

Explanation: The first customer needs a 5 back, and we have no money yet. The 5 from the second customer comes too late.

Check your understanding

Work out the answer for this input before you write any code.

bills = [5, 5, 10, 5, 5, 20, 10, 10]

Constraints

  • 1 ≤ bills.length ≤ 105
  • bills[i] is 5, 10 or 20.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.