Solution to LeetCode 1716 Calculate Money in Leetcode Bank.
LeetCode 1716
Calculate Money in Leetcode Bank (Easy). [link]
1] Math. Time complexity O(N). Space complexity O(1).
class Solution(object):
def totalMoney(self, n):
"""
:type n: int
:rtype: int
"""
week, day = 0, 1
res = 0
for i in range(n):
res += week + day
day += 1
if day == 8:
day = 1
week += 1
return res
2] Arithmetic progression. For each week, the money increases by 7. Sum up the money for the full weeks and the money for the remaining days. Time complexity O(1). Space complexity O(1).
class Solution(object):
def totalMoney(self, n):
"""
:type n: int
:rtype: int
"""
# for entire weeks
weekNum = n // 7
firstWeek = (1 + 7) * 7 // 2 # money in the first week
lastWeek = firstWeek + 7 * (weekNum - 1) # money in the last week
allWeeks = (firstWeek + lastWeek) * weekNum // 2 # sum all money
# for remaining days
dayNum = n % 7
firstDay = 1 + weekNum # money in the first day of the remaining days
lastDay = firstDay + dayNum - 1 # money in the last day of the remaining days
allDays = (firstDay + lastDay) * dayNum // 2 # sum all money
return allWeeks + allDays