leetcode 860 Lemonade Change

python:

class Solution:
    def lemonadeChange(self, bills):
        """
        :type bills: List[int]
        :rtype: bool
        """
        mon = dict()
        mon[5] = 0
        mon[10] = 0
        mon[20] = 0
        for i in bills:
            if i == 5:
                mon[i] += 1
            elif i == 10:
                mon[i] += 1
                mon[5] -= 1
                if mon[5] < 0:
                    return False
            else:
                if mon[10] >= 1 and mon[5] >= 1:
                    mon[10] -= 1
                    mon[5] -= 1
                elif mon[5] >= 3:
                    mon[5] -= 3
                else:
                    return False
        return True

c++:
 

class Solution {
public:
    bool lemonadeChange(vector<int>& bills) {
        int five=0, ten=0;
        for(int i=0; i<bills.size(); i++){
            if(bills[i] == 5)
                five++;
            else if(bills[i] == 10){
                five--;
                ten++;
            }
            else{
                if(ten>0){
                    five--;
                    ten--;
                }
                else
                    five -= 3;
            }
            if(five<0)
                return false;
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/MRxjh/article/details/81070287