Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Bank Account Rules

Protect an account's balance behind deposit and withdraw rules, rejecting invalid operations.

Bạn sẽ học được gì

  • Change state only through methods
  • Reject invalid amounts and overdrafts
  • Keep a count of rejected operations

Đề bài

Xem bản dịch

Encapsulation keeps an object's data private and only changes it through methods that enforce the rules. A bank account's balance can only change through deposit and withdraw.

Start with a balance of 0 and process the operations, each deposit <amount> or withdraw <amount>:

  • An amount that is 0 or negative is rejected.
  • A withdrawal larger than the current balance is rejected.
  • Otherwise the balance changes.

Implement bank_account_rules(operations).

Input

operations: The operations, in order.

Output

Return [final_balance, rejected_count].

Ràng buộc

0 ≤ number of operations ≤ 100,000

−10^9 ≤ amount ≤ 10^9

Ví dụ

Ví dụ 1
Đầu vào:
operations = ["deposit 100", "withdraw 30", "withdraw 200"]

Kết quả mong đợi:
expected = [70, 1]
Đầu vào:
std::vector<std::string> operations = {"deposit 100", "withdraw 30", "withdraw 200"};

Kết quả mong đợi:
std::vector<long long> expected = {70, 1};
Đầu vào:
string[] operations = new string[] {"deposit 100", "withdraw 30", "withdraw 200"};

Kết quả mong đợi:
long[] expected = new long[] {70, 1};

Giải thích

100 − 30 leaves 70; withdrawing 200 would overdraw the account, so it is rejected: [70, 1].

Ví dụ 2
Đầu vào:
operations = ["deposit -5", "withdraw 0", "deposit 10"]

Kết quả mong đợi:
expected = [10, 2]
Đầu vào:
std::vector<std::string> operations = {"deposit -5", "withdraw 0", "deposit 10"};

Kết quả mong đợi:
std::vector<long long> expected = {10, 2};
Đầu vào:
string[] operations = new string[] {"deposit -5", "withdraw 0", "deposit 10"};

Kết quả mong đợi:
long[] expected = new long[] {10, 2};

Giải thích

The negative deposit and the zero withdrawal are both rejected; the last deposit succeeds: [10, 2].

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

Keep the balance private and change it only in deposit and withdraw.

Gợi ý 2

Reject amounts of 0 or less before anything else.

Gợi ý 3

A withdrawal may not take the balance below zero.

Độ phức tạp mong đợi

O(number of operations) time, O(1) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.