This time our purpose is to help the lemonade stand owner to make a change judge, the customer only give the set 5, 10, 20 RMB, a cup of lemonade 5 yuan, the boss has no money, he can successfully change depends on our judgment.

Topic describes

860. Lemonade change

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:

Input: bills = [5,5,5,10,20] Output: true Explanation: We take three $5 bills from the first three customers, in order. At the fourth customer, we took a $10 bill and gave back $5. At the fifth customer, we gave back a $10 bill and a $5 bill. Since all customers got the correct change, we print true.Copy the code

Example 2:

Input: bills = [5,5,10,10,20] Output: false Explanation: We take two $5 bills from the first two customers in order. For the next two customers, we charge a $10 bill and give $5 back. For the last customer, we can't refund $15 because we only have two $10 bills. Since not every customer gets the correct change, the answer is false.Copy the code

Their thinking

Step by step judgment:

  1. If the customerWe can't handle $10 or $20 right here, tell your boss you can’t get change.
  2. Otherwise, to get into our normal judgment logic, first we have toAlways have ten and five dollars in change on handI don’t use ten and five and twenty because I can’t use it for change;
  • When you give us $5 we just let the number five count five plus one
  • Give us $10, and we need to know if we have $5 to change, if we have $5 — change out, ten++
  • For 20, we’re sureThe big ten is a priorityWe have to find fifteen, ten dollars a piece and five dollars a piece. Five — if you don’t have a ten, you need three fives: five-=3, otherwise you can’t find zeros

To the problem solving

/** * @param {number[]} bills * @return {boolean} */ var lemonadeChange = function(bills) { If ([10, 20]. Includes (bills [0])) return false. Let five = 0, ten = 0; for(bill of bills) { if(bill === 5) five++; If (bill === 10) {if(five){// If (bill === 10) { ten++; }else { return false; }} if(bill === 20) {if(ten &&five) {// Give the first change to 20 ten &&five ten--; five--; }else if(! ten && five >=3){ five -= 3; }else { return false; } } } return true; };Copy the code