Parcel-delivery app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-2762monotonic-deque
A parcel locker keeps groceries cold. Its sensor records the temperature once a minute, in tenths of a degree. The operator calls a run of consecutive readings steady when its highest reading minus its lowest is at most a limit.
A report counts the steady runs of a day. Two runs are different when they start or end at different minutes, and a single reading is a run. A day can have 100,000 readings, so checking every pair of start and end is too slow.
Write count_steady_runs(readings, limit).
readings[i] is the reading of minute i. A run is one or more consecutive readings.limit.int, so return a 64-bit number.Input: readings = [5, 4, 2, 4], limit = 2
Output: 8Use the same two queues as in the longest-run problem, but add up the runs. Let the right edge be r and the left edge be left. Every start from left to r gives a steady run that ends at r, which is r - left + 1 runs.
| Right | Reading | Left edge | Runs ending here | Total so far |
|---|---|---|---|---|
| 0 | 5 | 0 | 1 | 1 |
| 1 | 4 | 0 | 2 | 3 |
| 2 | 2 | 1 (spread 3 was too wide) | 2 | 5 |
| 3 | 4 | 1 | 3 | 8 |
Input: readings = [3, 3, 3], limit = 0
Output: 6Equal readings: every run is steady. There are 3 + 2 + 1 = 6 runs.
Input: readings = [1, 9, 1, 9], limit = 3
Output: 4Only the four single readings are steady.
1 ≤ length of readings ≤ 10^5, and 0 ≤ readings[i] ≤ 10^90 ≤ limit ≤ 10^9Checking every pair of start and end costs n × n / 2 steps, and the spread check adds more. For n = 100,000, that is 5 × 10^9 pairs.
The count itself can reach n × (n + 1) / 2. For n = 100,000, that is 5,000,050,000, which is more than a 32-bit int holds. The two queues make the pass O(n).