commit 501153be1cb20b688e3fcd6fe00427897a095712
parent db3649372b10388fb573d70920ee8e735c852c9f
Author: Jack Sangdahl <jack@pngu.org>
Date: Fri, 24 Oct 2025 21:15:59 -0600
1716. calcluate money in leetcode bank
Diffstat:
2 files changed, 9 insertions(+), 23 deletions(-)
diff --git a/calculate_money_bank.c b/calculate_money_bank.c
@@ -10,20 +10,11 @@
* at the end of the n'th day.
*/
+int prog(int next, int prev, int terms) { return (next + prev) * terms / 2; }
+
int totalMoney(int n) {
- int begin = 1, end = 7;
- int sum = 28, total = 0;
- while (n - 7) {
- total += sum;
- sum -= begin++;
- sum += ++end;
- n -= 7;
- }
- for (int i = 0; i < n; ++i) {
- total += begin;
- ++begin;
- }
- return total;
+ int q = n / 7, r = n % 7;
+ return prog(28, 28 + (q - 1) * 7, q) + prog(q + 1, q + r, r);
}
int main() {
diff --git a/calculate_money_bank.py b/calculate_money_bank.py
@@ -11,21 +11,16 @@ at the end of the n'th day.
class Solution(object):
+ def prog(self, next, prev, terms):
+ return (next + prev) * terms // 2
+
def totalMoney(self, n):
"""
:type n: int
:rtype: int
"""
- week = 0
- day = 1
- balance = 0
- for i in range(1, n + 1):
- balance += week + day
- day += 1
- if i % 7 == 0:
- week += 1
- day = 1
- return balance
+ q, r = divmod(n, 7)
+ return self.prog(28, 28 + (q - 1) * 7, q) + self.prog(q + 1, q + r, r)
if __name__ == "__main__":