LeetCode 题解工作台

计算力扣银行的钱

Hercy 想要为购买第一辆车存钱。他 每天 都往力扣银行里存钱。 最开始,他在周一的时候存入 1 块钱。从周二到周日,他每天都比前一天多存入 1 块钱。在接下来每一个周一,他都会比 前一个周一 多存入 1 块钱。 给你 n ,请你返回在第 n 天结束的时候他在力扣银行总共存了多少块钱。 示例 1:…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

根据题目描述,每周的存款情况如下: 第 1 周:1, 2, 3, 4, 5, 6, 7

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

Hercy 想要为购买第一辆车存钱。他 每天 都往力扣银行里存钱。

最开始,他在周一的时候存入 1 块钱。从周二到周日,他每天都比前一天多存入 1 块钱。在接下来每一个周一,他都会比 前一个周一 多存入 1 块钱。

给你 n ,请你返回在第 n 天结束的时候他在力扣银行总共存了多少块钱。

 

示例 1:

输入:n = 4
输出:10
解释:第 4 天后,总额为 1 + 2 + 3 + 4 = 10 。

示例 2:

输入:n = 10
输出:37
解释:第 10 天后,总额为 (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37 。注意到第二个星期一,Hercy 存入 2 块钱。

示例 3:

输入:n = 20
输出:96
解释:第 20 天后,总额为 (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96 。

 

提示:

  • 1 <= n <= 1000
lightbulb

解题思路

方法一:数学

根据题目描述,每周的存款情况如下:

第 1 周:1, 2, 3, 4, 5, 6, 7
第 2 周:2, 3, 4, 5, 6, 7, 8
第 3 周:3, 4, 5, 6, 7, 8, 9
...
第 k 周:k, k+1, k+2, k+3, k+4, k+5, k+6

存款天数为 nn,那么完整的周数为 k=n/7k = \lfloor n / 7 \rfloor,剩余天数为 b=nmod7b = n \mod 7

完整的 kk 周的存款总额,可以通过等差数列求和公式计算:

S1=k2×(28+28+7×(k1))S_1 = \frac{k}{2} \times (28 + 28 + 7 \times (k - 1))

剩余的 bb 天的存款总额,同样可以通过等差数列求和公式计算:

S2=b2×(k+1+k+1+b1)S_2 = \frac{b}{2} \times (k + 1 + k + 1 + b - 1)

最终的总存款金额为 S=S1+S2S = S_1 + S_2

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
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
speed

复杂度分析

指标
时间O(1)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Can the candidate explain the pattern behind the deposits?

  • question_mark

    Does the candidate attempt to use a direct mathematical formula for efficiency?

  • question_mark

    How well does the candidate simulate or optimize the process without looping through all the days?

warning

常见陷阱

外企场景
  • error

    Failing to account for the weekly increase on Mondays.

  • error

    Incorrectly simulating the deposit amount for each day of the week.

  • error

    Using an inefficient solution with a time complexity greater than O(1).

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Extend the problem to handle multiple months of deposits.

  • arrow_right_alt

    Change the weekly increment pattern to something more complex, such as an exponential growth.

  • arrow_right_alt

    Increase the maximum value of n to test the efficiency of the solution.

help

常见问题

外企场景

计算力扣银行的钱题解:数学·driven | LeetCode #1716 简单