LeetCode 860. Lemonade change (simple) greedy

topic

In the lemonade stalls, each cup of lemonade sold for 5dollars.

Customers line up to buy your product, (according to the bill billsthe order of payment) a purchase of a cup.

Each customer only buy a cup of lemonade, then you pay the 5dollar, 10the US dollar or 20US dollar. You have the right to change for each customer, which means that net trade is each customer to pay you 5dollars.

Note that you don't have any change at the beginning.

If you can give each customer the correct change, return true, otherwise return false.

Example 1:

输入:[5,5,5,10,20]
输出:true
解释:
前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。
第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。
第 5 位顾客那里,我们找还一张 10 美元的钞票和一张 5 美元的钞票。
由于所有客户都得到了正确的找零,所以我们输出 true。

Example 2:

输入:[5,5,10]
输出:true

Example 3:

输入:[10,10]
输出:false

Example 4:

输入:[5,5,10,10,20]
输出:false
解释:
前 2 位顾客那里,我们按顺序收取 2 张 5 美元的钞票。
对于接下来的 2 位顾客,我们收取一张 10 美元的钞票,然后返还 5 美元。
对于最后一位顾客,我们无法退回 15 美元,因为我们现在只有两张 10 美元的钞票。
由于不是每位顾客都得到了正确的找零,所以答案是 false。

English station most votes

analysis:

Intuition:
When the customer gives us $20, we have two options:

To give three $5 in return
To give one $5 and one $10.
On insight is that the second option (if possible) is always better than the first one.
Because two $5 in hand is always better than one $10


Explanation:
Count the number of $5 and $10 in hand.

if (customer pays with $5) five++;
if (customer pays with $10) ten++, five--;
if (customer pays with $20) ten--, five-- or five -= 3;

Check if five is positive, otherwise return false.


Time Complexity
Time O(N) for one iteration
Space O(1)
  • python
    def lemonadeChange(self, bills):
        five = ten = 0
        for i in bills:
            if i == 5: five += 1
            elif i == 10: five, ten = five - 1, ten + 1
            elif ten > 0: five, ten = five - 1, ten - 1
            else: five -= 3
            if five < 0: return False
        return True
  • java
    public boolean lemonadeChange(int[] bills) {
    
    
        int five = 0, ten = 0;
        for (int i : bills) {
    
    
            if (i == 5) five++;
            else if (i == 10) {
    
    five--; ten++;}
            else if (ten > 0) {
    
    ten--; five--;}
            else five -= 3;
            if (five < 0) return false;
        }
        return true;
    }
  • c++
  int lemonadeChange(vector<int> bills) {
        int five = 0, ten = 0;
        for (int i : bills) {
            if (i == 5) five++;
            else if (i == 10) five--, ten++;
            else if (ten > 0) ten--, five--;
            else five -= 3;
            if (five < 0) return false;
        }
        return true;
    }

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106945164