LeetCode 1716: Calculate Money in Leetcode Bank

Math

Problem Description

Explanation:

To solve this problem, we need to simulate Hercy's daily savings pattern based on the given rules. We can observe that each week follows an arithmetic progression, with the first day starting at 1 and increasing by 1 each day. The total savings after n days can be calculated by summing up the savings for each week and the remaining days.

  1. Calculate the total savings for complete weeks using the formula for the sum of an arithmetic progression.
  2. Calculate the savings for the remaining days after the last complete week.
  3. Add the savings from steps 1 and 2 to get the total amount of money Hercy will have at the end of the nth day.

:

Solutions

class Solution {
    public int totalMoney(int n) {
        int weeks = n / 7; // Number of complete weeks
        int total = 0;
        
        // Calculate total savings for complete weeks
        total += 28 * weeks + 7 * (weeks - 1) * weeks / 2;
        
        // Calculate savings for remaining days
        int remainingDays = n % 7;
        total += (2 * weeks + remainingDays - 1) * remainingDays / 2;
        
        return total;
    }
}

Loading editor...