Code
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five = 0, ten = 0;
for (int bill : bills) {
if (bill == 5) {
five++;
} else if (bill == 10 && five > 0) {
five--;
ten++;
} else if (bill == 20 && ten > 0 && five > 0) {
ten--;
five--;
} else if (bill == 20 && five >= 3) {
five -= 3;
} else {
return false;
}
}
return true;
}
}
Logic
- If you encounter 5s then increment the fives counter
- If you encounter a 10, then increment the tens counter and decrement the fives counter
- If you encounter a 20, then you have two options:
- 10 + 5 (decrement tens by 1 AND fives by 1 after checking if both of them are greater than or equal to 1)
- 5 * 3 (decrement fives by 3 after checking if its greater than or equal to 3)