We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Calculate Money in Leetcode Bank

Difficulty: Easy


Problem Description

Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday. Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.


Key Insights

  • The savings pattern follows a weekly cycle where the amount deposited increases each week.
  • Each week, starting from Monday, the deposits are:
    • Week 1: 1, 2, 3, 4, 5, 6, 7
    • Week 2: 2, 3, 4, 5, 6, 7, 8
    • Week 3: 3, 4, 5, 6, 7, 8, 9
  • The total savings can be calculated by determining how many complete weeks fit into n and accounting for the remaining days.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

To solve this problem, we can calculate the total amount of money deposited using a mathematical approach rather than simulating each day. The key steps are:

  1. Determine the number of complete weeks in n days and the remaining days.
  2. Calculate the total deposits for complete weeks using the formula for the sum of an arithmetic series.
  3. Add deposits for any remaining days after the last complete week.

Code Solutions

def totalMoney(n):
    # Calculate the number of complete weeks and remaining days
    weeks = n // 7
    days = n % 7
    
    # Total money from complete weeks
    total = weeks * (weeks + 1) * 7 // 2  # Sum of first 'weeks' numbers multiplied by 7
    # Add money from remaining days
    total += days * (weeks + 1) + (days * (days - 1)) // 2
    
    return total
← Back to All Questions