I observe that Hercy saves money in weekly cycles. Each week starts on Monday with an increasing base amount. The first week starts with 1, the second week starts with 2, and so on. For each full week, the total is the sum of 7 consecutive numbers starting from that base. So, for w full weeks, I can compute the sum using the arithmetic series formula. For the remaining r days (less than a week), I add the first r terms of the next week's sequence.
class Solution:
def totalMoney(self, n: int) -> int:
weeks, days = divmod(n, 7)
total = 7 * weeks * (weeks + 1) // 2 + 21 * weeks
total += days * (2 * weeks + days + 1) // 2
return total- Time: O(1)
- Space: O(1)