Monitoring~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1438monotonic-deque
A monitoring dashboard records the response time of a service once a minute, in milliseconds. The team calls a run of consecutive readings steady when its slowest reading minus its fastest reading is at most a limit.
On-call wants the length of the longest steady run in the list. A list can hold 200,000 readings, and a whole day can be steady, so extending a run from every start until it breaks is too slow.
Write longest_steady_run(readings, limit).
readings[i] is the response time of minute i. A run is one or more consecutive readings.limit.Input: readings = [30, 34, 31, 45, 40, 38, 41], limit = 6
Output: 3Keep two queues of positions inside the run. The highest queue holds readings that fall from the front to the back, so its front is the largest reading of the run. The lowest queue holds readings that rise, so its front is the smallest. When the spread is above the limit, move the left edge.
| Right | Reading | Left edge | Highest front | Lowest front | Spread | Run length |
|---|---|---|---|---|---|---|
| 0 | 30 | 0 | 30 | 30 | 0 | 1 |
| 1 | 34 | 0 | 34 | 30 | 4 | 2 |
| 2 | 31 | 0 | 34 | 30 | 4 | 3 |
| 3 | 45 | 3 (spread 15 was too wide) | 45 | 45 | 0 | 1 |
| 4 | 40 | 3 | 45 | 40 | 5 | 2 |
| 5 | 38 | 4 (spread 7 was too wide) | 40 | 38 | 2 | 2 |
| 6 | 41 | 4 | 41 | 38 | 3 | 3 |
The longest run has 3 readings.
Input: readings = [5, 5, 5, 5], limit = 0
Output: 4Equal readings have a spread of 0, so the whole list is one steady run.
Input: readings = [1, 9, 2, 8], limit = 3
Output: 1No two neighbouring readings are within 3 of each other, so only single readings are steady.
1 ≤ length of readings ≤ 2 × 10^5, and 0 ≤ readings[i] ≤ 10^90 ≤ limit ≤ 10^9Extending a run from every start costs up to n steps for each of n starts. For n = 200,000 and a whole list that is steady, that is about 2 × 10^10 steps.
Each reading joins each queue once and leaves it at most once, and the left edge only moves right. So the pass costs O(n). The difference of two readings is below 10^9, so it fits in a 32-bit int, but a careful solution subtracts in 64-bit.