2327. Number of People Aware of a Secret #2152
-
Topics: On day You are given an integer Given an integer Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the number of people who know a secret by the end of day Approach
Let's implement this solution in PHP: 2327. Number of People Aware of a Secret <?php
/**
* @param Integer $n
* @param Integer $delay
* @param Integer $forget
* @return Integer
*/
function peopleAwareOfSecret($n, $delay, $forget) {
$mod = 1000000007;
$dp = array_fill(0, $n + 1, 0);
$dp[1] = 1;
for ($i = 2; $i <= $n; $i++) {
$start = max(1, $i - $forget + 1);
$end = $i - $delay;
if ($start <= $end) {
for ($j = $start; $j <= $end; $j++) {
$dp[$i] = ($dp[$i] + $dp[$j]) % $mod;
}
}
}
$ans = 0;
$startDay = max(1, $n - $forget + 1);
for ($i = $startDay; $i <= $n; $i++) {
$ans = ($ans + $dp[$i]) % $mod;
}
return $ans;
}
// Test cases
echo peopleAwareOfSecret(6, 2, 4) . "\n"; // Output: 5
echo peopleAwareOfSecret(4, 1, 3) . "\n"; // Output: 6
?> Explanation:
This approach efficiently tracks the propagation of the secret over time using dynamic programming, ensuring correctness while adhering to the constraints. The complexity is O(n2), which is feasible given the constraints n ≤ 1000. |
Beta Was this translation helpful? Give feedback.
We need to determine the number of people who know a secret by the end of day
n
, considering that each person shares the secret with a new person every day starting fromdelay
days after discovering it, and forgets the secretforget
days after discovering it. The challenge is to model the propagation and forgetting of the secret over time efficiently.Approach
dp
wheredp[i]
represents the number of people who discover the secret on dayi
.dp[1] = 1
.i
(from 2 ton
), the number of new people who discover the secret is the sum of …