KatInterview

Yearly Account Balance with Conditional Monthly Service Charges

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashingsimulationhash-mapaggregation

Last updated

Simulate a year of account activity, applying a flat monthly charge unless a month has enough payments with a large enough total, and return the final balance.

Yearly Account Balance with Conditional Monthly Service Charges

An account starts the year with a given balance. During the year a list of transactions is applied to it, and at the close of each of the twelve months a flat service charge of 5 may be deducted.

Each transaction is a dictionary with these keys:

  • amount: a number, the size of the transaction
  • month: an integer from 1 to 12
  • type: a string, either "payment" or "deposit"

Rules

  1. A "payment" lowers the balance by its amount. Any other transaction (a "deposit") raises the balance by its amount.
  2. Every month from 1 through 12 is evaluated, including months with no transactions at all.
  3. For a given month, the service charge is waived only if both of these hold, counting only transactions of type "payment" in that month:
    • there are at least 3 payments, and
    • the sum of those payment amounts is strictly greater than 100.
  4. If the charge is not waived, 5 is subtracted from the balance for that month.
  5. Deposits never contribute to the waiver check.
  6. The balance may become negative; do not clamp it.
  7. Return the balance after all transactions and all twelve monthly charge decisions have been applied.

Write a function that takes the starting balance and the list of transactions, and returns the final balance as a float.

Constraints

  • initial_balance >= 0
  • 0 <= len(transactions) <= 1000
  • Each month is an integer in [1, 12]
  • Each type is either "payment" or "deposit"
  • The transactions may appear in any order

Examples

Example 1

Input: compute_year_end_balance(200, [{'amount': 50, 'month': 1, 'type': 'payment'}, {'amount': 30, 'month': 1, 'type': 'payment'}, {'amount': 40, 'month': 1, 'type': 'payment'}])

Output: 25

Example 2

Input: compute_year_end_balance(1000, [])

Output: 940

Example 3

Input: compute_year_end_balance(500, [{'amount': 20, 'month': 2, 'type': 'payment'}, {'amount': 30, 'month': 2, 'type': 'payment'}, {'amount': 40, 'month': 2, 'type': 'payment'}, {'amount': 200, 'month': 2, 'type': 'deposit'}])

Output: 550

Hints

Hint 1

Whether a month's charge is waived depends only on that month's payment count and payment total, never on the running balance.

Hint 2

Since everything is plain addition and subtraction, the order of operations does not affect the final balance. You can handle all transactions first, then all twelve charges.

Hint 3

Keep a payment count and a payment total for each month. Charge 5 when the count is below 3 or the total is not strictly above 100, and remember that empty months are charged too.