#2241

Design an ATM Machine

expert · 1010 · lc medium +32 · 44.6% accepted · 311 likes · top 27%

Description

An ATM stores banknotes in 5 denominations: 20, 50, 100, 200, and 500 dollars. It starts empty. Users may deposit or withdraw money.

During withdrawal, the machine always tries larger denominations first.

- For example, to withdraw $300 with 2 $50 notes, 1 $100 note, and 1 $200 note, the machine uses the $100 and $200 notes.

- However, trying to withdraw $600 with 3 $200 notes and 1 $500 note is rejected: the machine commits to the $500 note and cannot complete the remaining $100. It may not skip the $500 in favor of $200 notes.

Implement the ATM class:

- ATM() Initializes the ATM.

- void deposit(int[] banknotesCount) Adds notes in denomination order $20, $50, $100, $200, $500.

- int[] withdraw(int amount) Returns the note counts dispensed in the same denomination order, updating internal counts. Returns [-1] if the amount cannot be fulfilled exactly.

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]]

Example 2:

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.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16