LeetCode-in-Java

2241. Design an ATM Machine

Medium

There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.

When withdrawing, the machine prioritizes using banknotes of larger values.

Implement the ATM class:

Example 1:

Input

[“ATM”, “deposit”, “withdraw”, “deposit”, “withdraw”, “withdraw”]

[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]

Output: [null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]

Explanation:

ATM atm = new ATM();
atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,
                          // and 1 $500 banknote.
atm.withdraw(600);        // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote
                          // and 1 $500 banknote. The banknotes left over in the
                          // machine are [0,0,0,2,0].
atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.
                          // The banknotes in the machine are now [0,1,0,3,1].
atm.withdraw(600);        // Returns [-1]. The machine will try to use a $500 banknote
                          // and then be unable to complete the remaining $100,
                          // so the withdraw request will be rejected.
                          // Since the request is rejected, the number of banknotes
                          // in the machine is not modified.
atm.withdraw(550);        // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote
                          // and 1 $500 banknote.

Constraints:

Solution

public class ATM {
    private int[] nominals;
    private long[] counts;

    public ATM() {
        nominals = new int[] {20, 50, 100, 200, 500};
        counts = new long[5];
    }

    public void deposit(int[] banknotesCount) {
        for (int i = 0; i < 5; i++) {
            counts[i] += banknotesCount[i];
        }
    }

    public int[] withdraw(int amount) {
        int[] delivery = new int[5];
        long currentAmount = amount;
        for (int i = 4; i >= 0; i--) {
            if (currentAmount > nominals[i] * counts[i]) {
                delivery[i] = (int) counts[i];
            } else {
                delivery[i] = (int) currentAmount / nominals[i];
            }
            currentAmount += (long) -nominals[i] * delivery[i];
            if (currentAmount == 0) {
                break;
            }
        }
        if (currentAmount > 0) {
            return new int[] {-1};
        }
        for (int i = 0; i < 5; i++) {
            counts[i] -= delivery[i];
        }
        return delivery;
    }
}

/*
 * Your ATM object will be instantiated and called as such:
 * ATM obj = new ATM();
 * obj.deposit(banknotesCount);
 * int[] param_2 = obj.withdraw(amount);
 */