Calculate Money in Leetcode Bank Problem
Description
LeetCode Problem 1716.
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 n^th day.
Example 1:
Input: n = 4
Output: 10
Explanation: After the 4^th day, the total is 1 + 2 + 3 + 4 = 10.
Example 2:
Input: n = 10
Output: 37
Explanation: After the 10^th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2^nd Monday, Hercy only puts in $2.
Example 3:
Input: n = 20
Output: 96
Explanation: After the 20^th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
Constraints:
1 <= n <= 1000
Solution
Approach: Math
The deposits for each week 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
...
Week k: k, k+1, k+2, k+3, k+4, k+5, k+6
With n days there are k = n / 7 full weeks (integer division) and b = n % 7 days left over.
The weekly totals are 28, 35, 42, ..., an arithmetic sequence, so the full weeks add up to S1 = (28 + 28 + 7 * (k - 1)) * k / 2.
The remaining days deposit k + 1, k + 2, ..., k + b, so they add up to S2 = (k + 1 + k + b) * b / 2.
The answer is S1 + S2.
Complexity: O(1) time and O(1) space.
class Solution:
def totalMoney(self, n: int) -> int:
k, b = divmod(n, 7)
s1 = (28 + 28 + 7 * (k - 1)) * k // 2
s2 = (k + 1 + k + 1 + b - 1) * b // 2
return s1 + s2