SDE & MLE Prep

860. Lemonade Change

Problem

Lemonade costs $5. Customers in line each pay with a $5, $10 or $20 bill, and you start with no change. Decide whether you can give every customer correct change, in order.

Example: [5,5,5,10,20] → true; [5,5,10,10,20] → false

Track 5s and 10s. For a 20, prefer giving 10 + 5 (keeps 5s, which are more flexible) over 5 + 5 + 5.

Complexity: O(n).

class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        five = ten = 0
        for b in bills:
            if b == 5:
                five += 1
            elif b == 10:
                five, ten = five - 1, ten + 1
            elif ten:
                five, ten = five - 1, ten - 1
            else:
                five -= 3
            if five < 0:
                return False
        return True