1 Greedy algorithm (using undered_map)
class Solution {
private:
unordered_map<int, int> map;
public:
bool lemonadeChange(vector<int>& bills) {
if (bills[0] > 5) return false;
for (auto& b : bills) {
map[b] ++;
if (b == 10) {
if (map[5] < 1) return false;
map[5] --;
}
if (b == 20) {
if ((map[10] < 1 && map[5] < 3) || (map[10] > 0 && map[5] < 1))
return false;
if (map[10] > 0) {
map[10]--;
map[5]--;
} else
map[5] -= 3;
}
}
return true;
}
};
2 Greedy algorithm (using basic counter)
Since there is only the topic 5,10,20
, you can manually set 3
a counter instead of a data structure, but in general, it is still recommended to use a container
[Note] When initializing the counter, be sure to do this
int five = 0, ten = 0;
And don't be lazy, like this
int five, ten;
Because some compilers will automatically initialize 0, and some compilers will directly randomize the value, resulting in different results
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
if (bills[0] != 5) return false;
int five = 0, ten = 0;
for (auto& b : bills) {
if (b == 5) five++;
if (b == 10) {
if (five < 1) return false;
ten++;
five--;
}
if (b == 20) {
if (ten > 0 && five > 0) {
ten--;
five--;
} else if (ten < 1 && five >= 3)
five -= 3;
else return false;
}
}
return true;
}
};