Music streaming app~15 min2s · 256 MBtarget O(n) time, O(1) spacecomplexity · traversal
A music streaming app receives the number of plays in each minute as a stream. It marks a minute as busy when its count is strictly above the mean of all earlier minutes. The first minute has no earlier minutes, so it is never busy.
The stream never ends, so the service cannot keep the whole history. You will write the count of busy minutes using a few numbers, and see why that is enough.
Write count_above_running_mean(readings).
readings[i] is the number of plays in minute i.i, for i ≥ 1, is busy when readings[i] is strictly larger than the mean of readings[0] to readings[i - 1].Compare without division, so there is no rounding: readings[i] × i against the sum of the earlier readings.
Input: readings = [5, 3, 8, 6, 9, 2]
Output: 3Minute i is busy when reading × i is larger than the sum of the earlier readings.
| Minute | Reading | Sum before | Reading × minute | Busy? |
|---|---|---|---|---|
| 0 | 5 | 0 | 0 | no |
| 1 | 3 | 5 | 3 | no |
| 2 | 8 | 8 | 16 | yes |
| 3 | 6 | 16 | 18 | yes |
| 4 | 9 | 22 | 36 | yes |
| 5 | 2 | 31 | 10 | no |
Three minutes are busy.
Input: readings = [4, 4, 4, 4]
Output: 0Every reading equals the mean of the earlier ones, and equal is not busy. The answer is 0.
Input: readings = []
Output: 0With no minutes, there is nothing to mark: 0.
0 ≤ readings.length ≤ 100,000 (minutes)0 ≤ readings[i] ≤ 1,000,000 (plays in a minute)Adding up the earlier readings again for every minute costs about 5 × 10^9 additions, far beyond a second. The sum can pass 2 × 10^9, so use 64-bit integers. A running sum makes each minute cost one step.