【Rikko】860. Change for Lemonade

【Rikko】860. Change for Lemonade

  At the lemonade stand, a glass of lemonade sells for $5. Customers line up to buy your products, one cup at a time (in the order bills are paid).
  Each customer buys just one glass of lemonade and pays you $5, $10, or $20. You have to give each customer the correct change, which means the net transaction is that each customer pays you $5.
  Note that you don't have any change on hand at first.
  You are given an integer array bills, where bills[i] is the bill paid by the i-th customer. Return true if you were able to give each customer correct change, 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 sequence. 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 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.

Tips :

1 <= bills.length <= 1 0 5 10^5 105
bills[i] is either 5 or 10 or 20

answer

Greedy thinking, in the process of finding change, first look for the one with a larger denomination, and then find the one with a smaller denomination

class Solution {
    
    
    public boolean lemonadeChange(int[] bills) {
    
    
        int five = 0, ten = 0;
        for (int bill : bills) {
    
    
            //五块
            if (bill == 5) {
    
    
                five++;//直接收下
            }
            //十块
            else if (bill == 10) {
    
    
                if (five == 0) {
    
    
                    return false;//无法找零
                }
                five--;
                ten++;
            }
            //二十
            else {
    
    
                //当可以正确找零时,两种找零的方式中我们更倾向于第一种,因为需要使用 5美元的找零场景会比需要使用 10美元的找零场景多
                if (five > 0 && ten > 0) {
    
    
                    five--;
                    ten--;
                }
                //找5*3
                else if (five >= 3) {
    
    
                    five -= 3;
                }
                else {
    
    
                    return false;
                }
            }
        }
        return true;
    }
}

Guess you like

Origin blog.csdn.net/qq_44033208/article/details/131872926