[LeetCode] Design an ATM Machine

2241. Design an ATM Machine

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.

  • For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.
  • However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote.

Implement the ATM class:

  • ATM() Initializes the ATM object.
  • void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500.
  • int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case).
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
37
38
39
40
41
42
class ATM {
vector<long> money{0,0,0,0,0};
vector<long> rep{20,50,100,200,500};

vector<int> preCalculate(int amount) {
vector<int> res(5,0);
for(int i = 4; i >= 0; i--) {
amount -= rep[i] * (res[i] = min(1l * amount / rep[i], money[i]));
}
return res;
}
int getSum(vector<int>& a) {
int sum = 0;
for(int i = 0; i < 5; i++)
sum += rep[i] * a[i];
return sum;
}
public:
ATM() {}

void deposit(vector<int> b) {
for(int i = 0; i < 5; i++)
money[i] += b[i];
}

vector<int> withdraw(int amount) {
auto res = preCalculate(amount);
if(amount == getSum(res)) {
for(int i = 0; i < 5; i++)
money[i] -= res[i];
return res;
}
return {-1};
}
};

/**
* Your ATM object will be instantiated and called as such:
* ATM* obj = new ATM();
* obj->deposit(banknotesCount);
* vector<int> param_2 = obj->withdraw(amount);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/17/PS/LeetCode/design-an-atm-machine/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.