PythonGeek's Blog

LeetCode 2327 - Number of People Aware of a Secret

The problem asks us to return our answer modulo (10^9)+7, which is a good sign that we will not be able to brute force this.

Dynamic Programming + Sliding Window

The idea is to build up a dp array, where dp[i] represents the number of new sharers on that day. We store new sharers for dp because if we had stored total sharers instead, we could not calculate dp[i] based on dp[i-1] since some of the sharers from dp[i-1] may have forgotten by dp[i], but we won't know exactly how many. With new sharers, we can easily calculate dp[i] by adding the new people from dp[i-delay] who just started sharing, and subtracting the people from dp[i-forget] who just forgot. Then we just sum the new sharers from (n-forget+1) up to and including n, since the sharers who started sharing on (n-forget+1) will still be sharing by n.