1716. Calculate Money in Leetcode Bank
EasyView on LeetCode
Time: O(1)
Space: O(1)
Advertisement
Intuition
Maximize money on day n: earn on days 1, 4, 7, 10,... (every 3rd). Compare taking day n alone vs not.
Algorithm
- 1For n divisible by 3: earn on n/3 days (days 1,4,...,n). Else earn on floor(n/3) days + possibly one extra.
- 2Actually: max = (n//3)*2 if n%3==0, (n//3)*2 + (n%3 == 2 ? 1 : 0).
Common Pitfalls
- •Greedy: take triplets (3 days = ). Remainder of 1 day = extra, remainder of 2 = extra.
1716.cs
C#
// Approach: Math formula — sum complete weeks (arithmetic series of week totals) plus remaining days.
// Time: O(1) Space: O(1)
public class Solution
{
public int TotalMoney(int n)
{
// Calculate the number of complete weeks and remaining days
int completeWeeks = n / 7;
int remainingDays = n % 7;
// Calculate the sum for all complete weeks
// First week sum: 28 (1+2+3+4+5+6+7)
// Each subsequent week adds 7 more than the previous week
// This forms an arithmetic sequence: 28, 35, 42, ...
// Sum of arithmetic sequence: (first term + last term) * number of terms / 2
int firstWeekSum = 28;
int lastWeekSum = 28 + 7 * (completeWeeks - 1);
int totalFromCompleteWeeks = (firstWeekSum + lastWeekSum) * completeWeeks / 2;
// Calculate the sum for the remaining days
// Starting amount for remaining days: completeWeeks + 1
// The amounts form an arithmetic sequence starting from (completeWeeks + 1)
// Sum = (first day + last day) * number of days / 2
int firstDayOfRemainingWeek = completeWeeks + 1;
int lastDayOfRemainingWeek = completeWeeks + remainingDays;
int totalFromRemainingDays = (firstDayOfRemainingWeek + lastDayOfRemainingWeek) * remainingDays / 2;
return totalFromCompleteWeeks + totalFromRemainingDays;
}
}Advertisement
Was this solution helpful?