Skip to content

860. Lemonade Change 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  bool lemonadeChange(vector<int>& bills) {
    int fives = 0;
    int tens = 0;

    for (const int bill : bills) {
      if (bill == 5) {
        ++fives;
      } else if (bill == 10) {
        --fives;
        ++tens;
      } else {  // bill == 20
        if (tens > 0) {
          --tens;
          --fives;
        } else {
          fives -= 3;
        }
      }
      if (fives < 0)
        return false;
    }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public boolean lemonadeChange(int[] bills) {
    int fives = 0;
    int tens = 0;

    for (final int bill : bills) {
      if (bill == 5) {
        ++fives;
      } else if (bill == 10) {
        --fives;
        ++tens;
      } else { // bill == 20
        if (tens > 0) {
          --tens;
          --fives;
        } else {
          fives -= 3;
        }
      }
      if (fives < 0)
        return false;
    }

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def lemonadeChange(self, bills: list[int]) -> bool:
    fives = 0
    tens = 0

    for bill in bills:
      if bill == 5:
        fives += 1
      elif bill == 10:
        fives -= 1
        tens += 1
      else:  # bill == 20
        if tens > 0:
          tens -= 1
          fives -= 1
        else:
          fives -= 3
      if fives < 0:
        return False

    return True