#1716

Calculate Money in Leetcode Bank

Easy
MathArithmetic SeriesMathematical Summation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

Instead of simulating each day, we can use a mathematical approach to calculate the total deposits based on the number of complete weeks and the remaining days.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the number of complete weeks in n and the remaining days.
  2. 2Step 2: Use the formula for the sum of an arithmetic series to calculate the total for complete weeks.
  3. 3Step 3: Calculate the total for the remaining days using the last week's deposit amount.
solution.py5 lines
1def totalMoney(n):
2    weeks = n // 7
3    days = n % 7
4    total = (28 * weeks) + (weeks * (weeks - 1) // 2 * 7) + (days * (days + 1) // 2 + weeks * days)
5    return total

Complexity note: The time complexity is O(1) because we are performing a constant number of operations regardless of the size of n.

  • 1Understanding the pattern of deposits helps in deriving a formula for the total amount.
  • 2Recognizing the arithmetic series can simplify calculations significantly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.