Number of People Aware of a Secret LeetCode solution in C++

1
static int MOD = 1e9 + 7;
2
class Solution {
3
public:
4
int delay, forget;
5
vector<long> memo;
6
// Total number of people who would have found out about the secret by the nth
7
// day.
8
long dp(int n) {
9
if (!n) return 0;
10
if (memo[n] != -1) // Return cached result if exists.
11
return memo[n];
12
// Current contribution of 1 person who knows the secret
13
long result = 1;
14
for (int i = delay; i < forget; i++) // Number of people that the secret will be forwarded to
15
if (n - i >= 0) result = (result + dp(n - i)) % MOD;
16
return memo[n] = result;
17
}
18
int peopleAwareOfSecret(int n, int delay, int forget) {
19
this->delay = delay;
20
this->forget = forget;
21
memo.resize(n + 1, -1);
22
return (dp(n) - dp(n - forget) + MOD) % MOD; // Subtract the people who found out by the
23
// `n-forget` day as observed.
24
}
25
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0