[LeetCode] Number of People Aware of a Secret

2327. Number of People Aware of a Secret

On day 1, one person discovers a secret.

You are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards.

Given an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int peopleAwareOfSecret(int n, int delay, int forget) {
long long mod = 1e9 + 7, know = 0, wait = 1;
queue<pair<long long, long long>> delayq, forgetq;
delayq.push({delay + 1, 1});
forgetq.push({forget + 1, 1});
for(int i = delay + 1; i <= n; i++) {
if(!forgetq.empty() and forgetq.front().first == i) {
auto [_, c] = forgetq.front(); forgetq.pop();
know = (know - c + mod) % mod;
}
if(!delayq.empty() and delayq.front().first == i) {
auto [_, c] = delayq.front(); delayq.pop();
wait = (wait - c + mod) % mod;
know = (know + c) % mod;
}
if(know) {
delayq.push({i + delay, know});
forgetq.push({i + forget, know});
wait = (wait + know) % mod;
}
}
return (know + wait) % mod;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/03/PS/LeetCode/number-of-people-aware-of-a-secret/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.