Skip to content

2043. Simple Bank System

  • Time: Constructor: $O(|\texttt{balance}|)$, transfer(account1: int, account2: int, money: int), deposit(account: int, money: int), withdraw(account: int, money: int): $O(1)$
  • Space: $O(|\texttt{balance}|)$
 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
class Bank {
 public:
  Bank(vector<long long>& balance) : balance(move(balance)) {}

  bool transfer(int account1, int account2, long long money) {
    if (!isValid(account2))
      return false;
    return withdraw(account1, money) && deposit(account2, money);
  }

  bool deposit(int account, long long money) {
    if (!isValid(account))
      return false;
    balance[account - 1] += money;
    return true;
  }

  bool withdraw(int account, long long money) {
    if (!isValid(account))
      return false;
    if (balance[account - 1] < money)
      return false;
    balance[account - 1] -= money;
    return true;
  }

 private:
  vector<long long> balance;

  bool isValid(int account) {
    return 1 <= account && account <= balance.size();
  }
};
 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
public class Bank {
  public Bank(long[] balance) {
    this.balance = balance;
  }

  public boolean transfer(int account1, int account2, long money) {
    if (!isValid(account2))
      return false;
    return withdraw(account1, money) && deposit(account2, money);
  }

  public boolean deposit(int account, long money) {
    if (!isValid(account))
      return false;
    balance[account - 1] += money;
    return true;
  }

  public boolean withdraw(int account, long money) {
    if (!isValid(account))
      return false;
    if (balance[account - 1] < money)
      return false;
    balance[account - 1] -= money;
    return true;
  }

  private long[] balance;

  private boolean isValid(int account) {
    return 1 <= account && account <= balance.length;
  }
}
 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 Bank:
  def __init__(self, balance: List[int]):
    self.balance = balance

  def transfer(self, account1: int, account2: int, money: int) -> bool:
    if not self._isValid(account2):
      return False
    return self.withdraw(account1, money) and self.deposit(account2, money)

  def deposit(self, account: int, money: int) -> bool:
    if not self._isValid(account):
      return False
    self.balance[account - 1] += money
    return True

  def withdraw(self, account: int, money: int) -> bool:
    if not self._isValid(account):
      return False
    if self.balance[account - 1] < money:
      return False
    self.balance[account - 1] -= money
    return True

  def _isValid(self, account: int) -> bool:
    return 1 <= account <= len(self.balance)