0%

[筆記] Leetcode - 1716. Calculate Money in Leetcode Bank

https://leetcode.com/problems/calculate-money-in-leetcode-bank

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 nth day.

image

key: 總和用上底加下底乘高除二計算,再加上剩餘天數

第一週: 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
第二週: 2 + 3 + 4 + 5 + 6 + 7 + 8 = 28 + 7
第三週為: 3 + 4 + 5 + 6 + 7 + 8 + 9 = 28 + 7 x 2
.
.
.
N 週過去,總金額為: 28 + (28 + 7) + (28 + 7 × 2) + …… + [28 + 7 × (N - 1)]

{[28 + 28 + 7(N - 1)] × R} ÷ 2

最後記得加上不滿週的天數: (N + 1) + (N + 2) + … + (N + D)
[(N + 1) + (N + D)] x D ÷ 2

1
2
3
4
class Solution:
def totalMoney(self, n: int) -> int:
week, day = divmod(n, 7)
return (28 + 28 + 7 * (week - 1)) * week // 2 + (week * 2 + day + 1) * day // 2