Approach
# 模擬購買
Simulation.
# 如果顧客付20塊錢的話,我會優先找10塊錢(如果有的話)
If the customer pays with a 20, I will give them a 10 first.
# 接著是找3個5塊錢
Then give three 5-dollar coins.
Time Complexity
# n = number of bills
O(n)
Space Complexity
# n = number of bills
O(n)
Code
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int l = bills.size(), box_5 = 0, box_10 = 0;
for (int i = 0 ; i < l ; i++) {
if (bills[i] == 5) {
box_5++;
}
else if (bills[i] == 10) {
if (box_5 == 0) {
return false;
}
else {
box_5--;
box_10++;
}
}
else {
if (box_10 >= 1 && box_5 >= 1) {
box_10--;
box_5--;
}
else if (box_5 >= 3) {
box_5 -= 3;
}
else {
return false;
}
}
}
return true;
}
};