sagelearnai

Lemonade Change

Difficulty: Easy · Pattern: Greedy · LeetCode #860

Lemonade costs $5. Customers pay in order with a $5, $10 or $20 bill, and you start with no change. Return true if you can give every customer correct change.

Examples

text
[5,5,5,10,20]   →  true
[5,5,10,10,20]  →  false

Hints

  1. You only ever need to count your $5 and $10 bills. $20s are never usable as change.
  2. For a $20, which change should you give: $10 + $5, or three $5s?

Approach

For a $10, give back one $5. For a $20, prefer $10 + $5, and only use three $5s if you have no $10.

The greedy works because $5 bills are strictly more flexible: they can make change for both $10 and $20, while a $10 helps only with $20s. Saving the flexible bills never hurts.

Complexity

Time: O(n). Space: O(1).

Python solution
def lemonadeChange(bills):
    five = ten = 0
    for b in bills:
        if b == 5:
            five += 1
        elif b == 10:
            if not five:
                return False
            five -= 1
            ten += 1
        else:
            if ten and five:
                ten -= 1
                five -= 1
            elif five >= 3:
                five -= 3
            else:
                return False
    return True
JavaScript solution
function lemonadeChange(bills) {
  let five = 0, ten = 0;
  for (const b of bills) {
    if (b === 5) five++;
    else if (b === 10) { if (!five) return false; five--; ten++; }
    else if (ten && five) { ten--; five--; }
    else if (five >= 3) five -= 3;
    else return false;
  }
  return true;
}