Design an ATM Machine LeetCode solution in Java

1
class ATM {
2
long[] notes =
3
new long[5]; // Note: use long[] instead of int[] to avoid getting error in large testcases
4
int[] denoms;
5

6
public ATM() {
7
denoms = new int[] {20, 50, 100, 200, 500}; // create an array to represent money value.
8
}
9

10
public void deposit(int[] banknotesCount) {
11
for (int i = 0; i < banknotesCount.length; i++) {
12
notes[i] += banknotesCount[i]; // add new deposit money to existing
13
}
14
}
15

16
public int[] withdraw(int amount) {
17
int[] result =
18
new int
19
[5]; // create result array to store quantity of each notes we will be using to withdraw
20
// "amount"
21
for (int i = 4; i >= 0; i--) {
22
if (amount >= denoms[i]) {
23
int quantity =
24
(int)
25
Math.min(
26
notes[i],
27
amount
28
/ denoms[
29
i]); // pick the minimum quanity. because if say, amount/denoms[i] gives
30
// 3 but you only have 1 note. so you have to use 1 only instead of
31
// 3
32
amount -= denoms[i] * quantity; // amount left = 100
33
result[i] = quantity;
34
}
35
}
36
if (amount != 0) {
37
return new int[] {-1};
38
}
39
for (int i = 0; i < 5; i++) {
40
notes[i] -= result[i];
41
} // deduct the quantity we have used.
42
return result;
43
}
44
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0