Title description:
At the lemonade stand, each glass of lemonade sells for $5. Customers line up to buy your products, (in the order of bills paid) one cup at a time. Each customer only buys a glass of lemonade, and then pays you $5, $10, or $20. You must give each customer the correct change, which means that the net transaction is that each customer pays you $5. Note that you don't have any change in hand at the beginning. If you can give each customer the correct change, return true, otherwise return false.
prompt:
- 0 <= bills.length <= 10000
- bills[i] is either 5 or 10 or 20
Example 1:
Input: [5,5,5,10,20]
Output: true
Explanation:
- From the first 3 customers, we collect 3 5 USD bills in order.
- From the 4th customer, we received a $10 bill and returned $5.
- For the fifth customer, we returned a 10 dollar bill and a 5 dollar bill.
- Since all customers got the correct change, we output true.
Example 2:
Input: [5,5,10]
Output: true
Example 3:
Input: [10,10]
Output: false
Example 4:
Input: [5,5,10,10,20]
Output: false
Explanation:
- From the first 2 customers, we collect 2 US$5 bills in order.
- For the next 2 customers, we charge a $10 bill and return $5.
- For the last customer, we cannot return $15 because we now only have two $10 bills.
- Since not every customer gets the correct change, the answer is false.
code show as below:
class Solution {
public boolean lemonadeChange(int[] bills) {
int n = bills.length;
int a = 0, b = 0;
if (n == 0) {
return true;
}
if (bills[0] > 5) {
return false;
}
for (int bill : bills) {
if (bill == 5) {
a++;
} else if (bill == 10) {
a--;
if (a < 0) {
return false;
}
b++;
} else if (bill == 20) {
if (b >= 1 && a >= 1) {
b--;
a--;
} else if (b == 0 && a >= 3) {
a -= 3;
} else {
return false;
}
}
}
return true;
}
}
Results of the: