The title
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.
Source: LeetCode leetcode-cn.com/problems/le…
Their thinking
Change depends on what denominations you have. There are only $5 and $10 bills you can use for change, so you have to write down the number of those two bills every time you get change.
- When you hit $5, you don’t need change, you increase the amount by 1
- When you encounter $10, you check the amount of $5 and make change if it’s greater than 0. You subtract 1 from the amount of $5 and add 1 to the amount of $10
- There are two ways to get change for A $20 bill: A:10 +5, B:5 +5 +5, 5 is more important, and 10+5 is preferred. If neither of the two ways is available, it means you can’t get change
Code implementation
var lemonadeChange = function (bills) { let five = 0 let ten = 0 let valid = true bills.forEach(bill => { if (bill === If (bill === 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) {if (bill == 10) { If (five > 0) {five-- ten++} else {valid = false}} else {if (five > 0) {five-- ten++} else {valid = false}} else { If (ten > 0 && five > 0) {ten-- five--} else if (five >= 3) {five- = 3} else {valid = false}}}) return is preferred valid };Copy the code
If there are mistakes welcome to point out, welcome to discuss together!