Subject to introduce
At the lemonade stand, a glass of lemonade costs $5. Customers line up to buy your product, one cup at a time (in bill bill order).
Each customer buys a glass of lemonade and pays you $5, $10 or $20. You have to give each customer the correct change, so the net transaction is that each customer pays you $5.
Notice that you don’t have any change to start with.
I’m going to give you an array of integers bills, where Bills [I] is the bill paid by the ith customer. Return true if you gave each customer the correct change, false otherwise.
Example 1
Enter: bills = [5.5.5.10.20] output:trueExplanation: the former3From our customers, we collect them in order3 张 5Dollar bills. The first4From a customer, we charge one10Dollar bills and return them5The dollar. The first5A customer. We'll give you back one10Dollar bills and one5Dollar bills. Since all customers get the correct change, we exporttrue.Copy the code
Example 2
Enter: bills = [5.5.10.10.20] output:falseExplanation: the former2From our customers, we collect them in order2 张 5Dollar bills. For the next2One customer, we charge one10Dollar bills and return them5The dollar. For the last customer, we can't return it15Us dollars, because we only have two bills10Dollar bills. Since not every customer gets the correct change, the answer isfalse.Copy the code
Example 3
Enter: bills = [5.5.10] output:true
Copy the code
Example 4
Enter: bills = [10.10] output:false
Copy the code
Tip:
1 <= bills.length <= 10^5
bills[i]
not5
is10
or20
Leetcode -860 Lemonade change B station video
Their thinking
1. Create two variables five and ten to record the amount of $5 and $10 we have 2. Walk through the Bills array
- When the value is 5, you don’t need change, you add one to five
- When the value is 10, you need change 5, so the number of ten is increased by 1, and the number of five is decreased by 1
- When the value is 20, we need change 15, so we can change 10 + 5, or 5 + 5 + 5, for ten minus 1, five minus 1, or five-3, since 5 can give change to either 10 or 20, So 10 + 5 is preferred when you have 10
3. If we can’t find zero on a bill, return false, game over 4. Return true when we can successfully find zero for all bills
The problem solving code
var lemonadeChange = function(bills) {
let five = ten = 0
for (let i = 0; i < bills.length; i++) {
switch(bills[i]) {
case 5:
five++
break;
case 10:
if(! five)return false
ten++
five--
break
case 20:
if(! five || (five <3 && !ten)) return false
if (ten) {
ten--
five--
} else {
five -= 3
}
break}}return true
};
Copy the code
So that’s the answer to this question, Welcome to see my other article [luffy]_ ring list [Luffy]_ happy number [Luffy]_ reverse list [Luffy]_ reverse list [Luffy]_K group of flipped list [Luffy]_ rotation list [Luffy]_ pairwise swap list of nodes [Luffy]_ recent requests [luffy]_ KTH number [Luffy]_ Intimate string