Design an ATM Machine
You want to implement the ATM class to handle deposit and withdrawal of money with specific constraints. Here is the implementation:
- Initialize the ATM object to keep track of banknotes.
- Deposit method to deposit banknotes in specific denominations.
- Withdraw method to attempt to withdraw an amount, prioritizing larger denominations, and returning an array of used banknotes or
[-1]
if the withdrawal is not possible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| from typing import List
class ATM:
def __init__(self):
# Initialize banknotes with 0 counts
self.banknotes = [0] * 5
def deposit(self, banknotesCount: List[int]) -> None:
# Increment the counts for each denomination
for i in range(5):
self.banknotes[i] += banknotesCount[i]
def withdraw(self, amount: int) -> List[int]:
# Temporary list to keep track of the notes used for this transaction
notes_used = [0] * 5
denominations = [500, 200, 100, 50, 20]
for i in range(5):
if amount >= denominations[i]:
# Find how many notes are needed
needed_notes = amount // denominations[i]
# Use the minimum of the notes needed and the notes available
used_notes = min(needed_notes, self.banknotes[4 - i])
# Update the counts
notes_used[4 - i] = used_notes
self.banknotes[4 - i] -= used_notes
amount -= used_notes * denominations[i]
# If there is still amount left, the transaction is not possible
if amount > 0:
# Restore the banknotes as the transaction failed
for i in range(5):
self.banknotes[4 - i] += notes_used[4 - i]
return [-1]
return notes_used
|
Example
You can use this class in the following way:
1
2
3
4
5
6
| atm = ATM()
atm.deposit([0,0,1,2,1])
print(atm.withdraw(600)) # Output: [0,0,1,0,1]
atm.deposit([0,1,0,1,1])
print(atm.withdraw(600)) # Output: [-1]
print(atm.withdraw(550)) # Output: [0,1,0,0,1]
|
Key Takeaways
- Deposit simply adds the banknotes to the ATM’s internal state.
- Withdraw carefully considers the constraints by prioritizing larger denominations and ensuring that the withdrawal is possible.
- If the withdrawal is not possible, the method returns
[-1]
, and the state of the ATM does not change.