Directory link:
Lituo Programming Problems - Summary of Solutions_Share+Records-CSDN Blog
GitHub synchronous brushing project:
https://github.com/September26/java-algorithms
Link to the original title: Likou
describe:
At the lemonade stand, a glass of lemonade sells for 5
US dollars. Customers line up to buy your product, (in bills
order of bill payment) one drink at a time.
Each customer just buys a glass of lemonade and pays you 5
dollars, 10
dollars, or 20
dollars. You have to give each customer the correct change, which means the net transaction is each customer paying you 5
dollars.
Note that you don't have any change on hand at first.
Give you an array of integers bills
, which bills[i]
is i
the bill paid by the first customer. If you can give each customer correct change, return true
, otherwise return false
.
Example 1:
Input: bills = [5,5,5,10,20] Output: true Explanation: For the first 3 customers, we collect 3 $5 bills in order. For the 4th customer, we take a $10 bill and give back $5. With the 5th customer, we return a $10 bill and a $5 bill. Since all customers got the correct change, we output true.
Example 2:
Input: bills = [5,5,10,10,20] Output: false Explanation: For the first 2 customers, we collect 2 $5 bills in sequence. For the next 2 customers, we take a $10 bill and give back $5. For the last customer, we can't refund the $15 because we only have two $10 bills right now. Since not every customer gets the correct change, the answer is false.
hint:
1 <= bills.length <= 105
bills[i]
either5
or10
_20
Problem-solving ideas:
code:
class Solution {
public:
bool lemonadeChange(vector<int> &bills)
{
int num5 = 0;
int num10 = 0;
for (int i = 0; i < bills.size(); i++)
{
int bill = bills[i];
if (bill == 5)
{
num5++;
}
else if (bill == 10)
{
num5--;
num10++;
}
else if (bill == 20)
{
if (num10 == 0)
{
num5 = num5 - 3;
}
else
{
num5--;
num10--;
}
}
if (num10 < 0 || num5 < 0)
{
return false;
}
}
return true;
}
};