Monitoring~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-907monotonic-stack · stacks
A monitoring system records the number of failed health checks in each hour. A weekly report rates every run of consecutive hours by its quietest hour: the lowest count in that run.
The report adds up the ratings of every possible run, which means every choice of a first hour and a last hour. The total grows large, so the report shows it modulo 1,000,000,007. A report can cover up to 100,000 hours.
Write sum_of_run_minimums(readings).
readings is a list of whole numbers, one for each hour, in order.n hours has n × (n + 1) / 2 runs.Input: readings = [4, 2, 5, 2, 6]
Output: 39Instead of listing the 15 runs, count for each hour how many runs it is the lowest of. Hour m is the lowest of a run when the run starts after the nearest lower hour on its left. The run must also end before the nearest lower-or-equal hour on its right. A stack finds both edges in one pass.
| Hour | Reading | Starts (hours back to the lower hour on its left) | Ends (hours up to the lower-or-equal hour on its right) | Runs | Added (reading × runs) |
|---|---|---|---|---|---|
| 0 | 4 | 1 | 1 (hour 1 is lower) | 1 | 4 |
| 1 | 2 | 2 (no lower hour on the left) | 2 (hour 3 is equal) | 4 | 8 |
| 2 | 5 | 1 | 1 (hour 3 is lower) | 1 | 5 |
| 3 | 2 | 4 (hour 1 is equal, not lower) | 2 (the end of the list) | 8 | 16 |
| 4 | 6 | 1 | 1 | 1 | 6 |
The total is 4 + 8 + 5 + 16 + 6 = 39. Hours 1 and 3 are equal. A run that holds both is counted for hour 3, the later one, because the right edge of hour 1 stops at hour 3.
Input: readings = [2, 2]
Output: 6The runs are [2], [2] and [2, 2]. Each has minimum 2, so the total is 6.
Input: readings = [5]
Output: 5One hour makes one run, with minimum 5.
1 ≤ number of hours ≤ 10^51 ≤ each reading ≤ 10^5A plan that visits every run costs n × (n + 1) / 2 steps: about 5 × 10^9 for 100,000 hours. That is too slow.
So the work must be close to n steps in all. Each hour should be handled a constant number of times, and the runs counted, not listed.