1716. Calculate Money in Leetcode Bank (LeetCode) (solution: C++, C#)

 

Problem Name: 1716. Calculate Money in Leetcode Bank
Problem Link: https://leetcode.com/problems/calculate-money-in-leetcode-bank/
Difficulty: Easy
Tag: Math
Language: C# | C++
OJ: LeetCode

Algorithm:
1.Calculate Full Cycles:
✅Determine the number of complete 7-week cycles in the total number of weeks.

2.Update Remaining Weeks:
✅Update the total number of weeks to be the remainder after dividing by 7. This represents the remaining weeks after completing full cycles.

3.Initialize Sum:
✅Initialize a variable sum to keep track of the total amount of money.

4.Calculate Sum for Completed Cycles:
✅Iterate through each completed 7-week cycle.
✅Add a fixed amount of 21 units plus an additional amount based on the cycle number multiplied by 7.

5.Calculate Sum for Remaining Weeks:
✅Iterate through the remaining weeks.
✅Add the portion (number of full cycles) to each remaining week.

6.Return Total Sum:
✅Return the calculated total sum.

Code(C#)
public class Solution
{
    public int TotalMoney(int n)
    {
        int portion = (n / 7);
        n %= 7;
        int sum = 0;
        for(int i=1; i<=portion; i++)
            sum += (21 + (i * 7));
        for (int i = 1; i <= n; i++)
            sum += (portion+i);
        return sum;
    }
}

Code(C++)
class Solution {
public:
    int totalMoney(int n) {
        int portion = (n / 7);
        n %= 7;
        int sum = 0;
        for(int i=1; i<=portion; i++)
            sum += (21 + (i * 7));
        for (int i = 1; i <= n; i++)
            sum += (portion+i);
        return sum;
    }
};