LeetCode 题解工作台
知道秘密的人数
在第 1 天,有一个人发现了一个秘密。 给你一个整数 delay ,表示每个人会在发现秘密后的 delay 天之后, 每天 给一个新的人 分享 秘密。同时给你一个整数 forget ,表示每个人在发现秘密 forget 天之后会 忘记 这个秘密。一个人 不能 在忘记秘密那一天及之后的日子里分享秘密。…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们用一个差分数组 来记录第 天知道秘密的人数变化情况,用一个数组 来记录第 天新得知秘密的人数。 那么,对于第 天新得知秘密的 个人来说,他们会在 $[i+\text{delay}, i+\text{forget})$ 这段时间内每天都能分享给另外 个人。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
在第 1 天,有一个人发现了一个秘密。
给你一个整数 delay ,表示每个人会在发现秘密后的 delay 天之后,每天 给一个新的人 分享 秘密。同时给你一个整数 forget ,表示每个人在发现秘密 forget 天之后会 忘记 这个秘密。一个人 不能 在忘记秘密那一天及之后的日子里分享秘密。
给你一个整数 n ,请你返回在第 n 天结束时,知道秘密的人数。由于答案可能会很大,请你将结果对 109 + 7 取余 后返回。
示例 1:
输入:n = 6, delay = 2, forget = 4 输出:5 解释: 第 1 天:假设第一个人叫 A 。(一个人知道秘密) 第 2 天:A 是唯一一个知道秘密的人。(一个人知道秘密) 第 3 天:A 把秘密分享给 B 。(两个人知道秘密) 第 4 天:A 把秘密分享给一个新的人 C 。(三个人知道秘密) 第 5 天:A 忘记了秘密,B 把秘密分享给一个新的人 D 。(三个人知道秘密) 第 6 天:B 把秘密分享给 E,C 把秘密分享给 F 。(五个人知道秘密)
示例 2:
输入:n = 4, delay = 1, forget = 3 输出:6 解释: 第 1 天:第一个知道秘密的人为 A 。(一个人知道秘密) 第 2 天:A 把秘密分享给 B 。(两个人知道秘密) 第 3 天:A 和 B 把秘密分享给 2 个新的人 C 和 D 。(四个人知道秘密) 第 4 天:A 忘记了秘密,B、C、D 分别分享给 3 个新的人。(六个人知道秘密)
提示:
2 <= n <= 10001 <= delay < forget <= n
解题思路
方法一:差分数组
我们用一个差分数组 来记录第 天知道秘密的人数变化情况,用一个数组 来记录第 天新得知秘密的人数。
那么,对于第 天新得知秘密的 个人来说,他们会在 这段时间内每天都能分享给另外 个人。
答案为 。
时间复杂度 ,空间复杂度 。其中 为题目给定的整数。
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
m = (n << 1) + 10
d = [0] * m
cnt = [0] * m
cnt[1] = 1
for i in range(1, n + 1):
if cnt[i]:
d[i] += cnt[i]
d[i + forget] -= cnt[i]
nxt = i + delay
while nxt < i + forget:
cnt[nxt] += cnt[i]
nxt += 1
mod = 10**9 + 7
return sum(d[: n + 1]) % mod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n * forget) because we iterate over each day and track up to 'forget' days of states. Space complexity is O(n * forget) for the DP table but can be optimized to O(forget) using rolling arrays. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Emphasize your DP state and why each state represents people aware for exact days.
- question_mark
Explain how the delay and forget constraints affect the sharing process.
- question_mark
Discuss rolling array optimization to reduce space complexity.
常见陷阱
外企场景- error
Forgetting to exclude people from sharing on the day they forget.
- error
Incorrectly summing states, counting those who already forgot.
- error
Confusing delay and forget days, leading to off-by-one errors in DP indices.
进阶变体
外企场景- arrow_right_alt
Calculate the total number of people aware if multiple people discover the secret on different days.
- arrow_right_alt
Find the earliest day when the number of people aware reaches a target value.
- arrow_right_alt
Modify the problem to allow sharing with multiple people per day instead of just one.