leetcode

Calculate Money in Leetcode Bank - Link

Question 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.


Constraints


Approach

Simulate the process day by day. Start with monday = 1, money = 1, sum = 0, day = 1.

For each day, add money to sum, increment money, increment day.

If day == 8, reset day to 1, increment monday, set money to monday.

This way, each week starts with increasing monday amount, and within week increases by 1 each day.


Dry Run

Example Input: n = 4

Total = 10


Solution

class Solution {
    public int totalMoney(int n) {
        int monday=1;
        int money=1;
        int sum=0;
        int day=1;

        while(n>0){
            sum+=money++;
            day++;
            if(day==8){
                money=++monday;
                day=1;
            }
            n--;
        }  
        return sum;      
    }
}

Time and Space Complexity

Back to All Problems