Skip to content

2241. Design an ATM Machine 👎

  • Time: Constructor: $O(1)$, deposit(banknotesCount: List[int]): $O(1)$, withdraw(amount: int): $O(1)$
  • Space:
 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
class ATM {
 public:
  ATM() : bank(5) {}

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

  vector<int> withdraw(int amount) {
    vector<int> withdrew(5);

    for (int i = 4; i >= 0; --i) {
      withdrew[i] = min(bank[i], static_cast<long long>(amount) / banknotes[i]);
      amount -= withdrew[i] * banknotes[i];
    }

    if (amount)
      return {-1};

    for (int i = 0; i < 5; ++i)
      bank[i] -= withdrew[i];
    return withdrew;
  }

 private:
  vector<int> banknotes{20, 50, 100, 200, 500};
  vector<long long> bank;
};
 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
class ATM {
  public void deposit(int[] banknotesCount) {
    for (int i = 0; i < 5; ++i)
      bank[i] += banknotesCount[i];
  }

  public int[] withdraw(int amount) {
    int[] withdrew = new int[5];

    for (int i = 4; i >= 0; --i) {
      withdrew[i] = (int) Math.min(bank[i], (long) amount / banknotes[i]);
      amount -= withdrew[i] * banknotes[i];
    }

    if (amount > 0)
      return new int[] {-1};

    for (int i = 0; i < 5; ++i)
      bank[i] -= withdrew[i];
    return withdrew;
  }

  private int[] banknotes = {20, 50, 100, 200, 500};
  private long[] bank = new long[5];
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ATM:
  def __init__(self):
    self.banknotes = [20, 50, 100, 200, 500]
    self.bank = [0] * 5

  def deposit(self, banknotesCount: List[int]) -> None:
    for i in range(5):
      self.bank[i] += banknotesCount[i]

  def withdraw(self, amount: int) -> List[int]:
    withdrew = [0] * 5

    for i in reversed(range(5)):
      withdrew[i] = min(self.bank[i], amount // self.banknotes[i])
      amount -= withdrew[i] * self.banknotes[i]

    if amount:
      return [-1]

    for i in range(5):
      self.bank[i] -= withdrew[i]
    return withdrew