At a lemonade stand, each lemonade costs$5.

Customers are standing in a queue to buy from you, and order one at a time (in the order specified bybills).

Each customer will only buy one lemonade and pay with either a$5,$10, or$20bill. You must provide the correct change to each customer, so that the net transaction is that the customer pays $5.

Note that you don't have any change in hand at first.

Returntrue if and only if you can provide every customer with correct change.

这题要仔细考虑集中情况,如果钞票是5刀,不需要找钱,如果钞票是10刀,要找5刀,如果钞票是20刀,要么找一张10刀一张5刀,要么找3张5刀,而且要优先找一张10刀一张5刀,因为5刀越多越灵活,越容易满足要求

class Solution {
    public boolean lemonadeChange(int[] bills) {
        if(bills == null || bills.length == 0)
            return true;

        int count5 = 0;
        int count10 = 0;

        for(int i = 0; i < bills.length; i++) {
            if(bills[i] == 5) {
                count5++;
            } else if(bills[i] == 10) {
                if(count5 == 0)
                    return false;

                count5--;
                count10++;
            } else if(bills[i] == 20) {
                if(count10 > 0 && count5 > 0) {
                    count5--;
                    count10--;
                } else if(count5 >= 3) {
                    count5 -= 3;
                } else {
                    return false;
                }
            }
        }

        return true;
    }
}

results matching ""

    No results matching ""