Lemonade Change

IF
AlgoAxiomStaff Engineers
JSTS
Easy20 mins

At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you, and they pay with either a $5, $10, or $20 bill (represented by the bills array).

You must provide the correct change to each customer so that the net transaction is that each customer pays $5. Note that you don't have any change in hand at first.

Return true if you can provide every customer with the correct change, or false otherwise.

Examples

Example 1:

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

Output: true

Explanation:

  • Customer 1 pays $5 — no change needed. (fives: 1)
  • Customer 2 pays $5 — no change needed. (fives: 2)
  • Customer 3 pays $5 — no change needed. (fives: 3)
  • Customer 4 pays $10 — give back one $5. (fives: 2, tens: 1)
  • Customer 5 pays $20 — give back one $10 + one $5. (fives: 1, tens: 0)

Example 2:

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

Output: false

Explanation:

  • Customer 1 pays $5 — no change needed. (fives: 1)
  • Customer 2 pays $5 — no change needed. (fives: 2)
  • Customer 3 pays $10 — give back one $5. (fives: 1, tens: 1)
  • Customer 4 pays $10 — give back one $5. (fives: 0, tens: 2)
  • Customer 5 pays $20 — need one $10 + one $5, but we have no $5 bills. Cannot make change!

Example 3:

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

Output: false

Explanation: For the first $20, we give one $10 + one $5 — but we have no $10s, so we give three $5s. For the second $20, we only have one $5 left and cannot make $15 in change.

Constraints

  • 1 <= bills.length <= 10⁵
  • bills[i] is either 5, 10, or 20
Source: Greedy Techniques pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle