The problem is taken from LeetCode and is as follows:
At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you, and they order one at a time (in the order specified by the given integer array bills
where bills[i]
is the bill the i-th
customer pays). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer based only on the bills you have previously received.
Return true
if you can provide every customer with the correct change, or false
otherwise.
To ensure the problem is fully understood, let’s clarify potential questions:
bills
array guaranteed to only contain valid bill denominations (i.e., $5, $10, $20)?
bills
only contains these denominations.To solve this problem, follow these steps:
Maintain a count for $5 and $10 bills since $20 bills don’t need to be tracked individually for giving change (as they can’t contribute to giving any meaningful change).
false
.false
.true
.Here’s the solution implemented in C++:
#include <vector>
bool lemonadeChange(std::vector<int>& bills) {
int count5 = 0, count10 = 0;
for (int bill : bills) {
if (bill == 5) {
count5++;
} else if (bill == 10) {
if (count5 <= 0) return false;
count5--;
count10++;
} else { // bill == 20
if (count10 > 0 && count5 > 0) {
count10--;
count5--;
} else if (count5 >= 3) {
count5 -= 3;
} else {
return false;
}
}
}
return true;
}
O(n)
, where n
is the number of elements in the bills
array. We traverse the array once.O(1)
, as we only use a constant amount of extra space to store the counts of $5 and $10 bills.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?