LeetCode 860: Lemonade Change

ArrayGreedy

Problem Description

Explanation

To solve this problem, we can simulate the process of providing change to customers. We maintain the count of $5 and $10 bills we have in hand. Whenever a customer pays with $5, we don't need to give any change. If a customer pays with $10, we give back $5 if we have it. If a customer pays with $20, we try to give back a $10 bill and a $5 bill if we have them, or three $5 bills. If at any point we cannot provide the correct change, we return false.

Solutions

class Solution {
    public boolean lemonadeChange(int[] bills) {
        int count5 = 0, count10 = 0;

        for (int bill : bills) {
            if (bill == 5) {
                count5++;
            } else if (bill == 10) {
                if (count5 == 0) {
                    return false;
                }
                count5--;
                count10++;
            } else {
                if (count10 > 0 && count5 > 0) {
                    count10--;
                    count5--;
                } else if (count5 >= 3) {
                    count5 -= 3;
                } else {
                    return false;
                }
            }
        }

        return true;
    }
}

Loading editor...