Monitoring~40 min2s · 256 MBtarget O(n log n) time, O(n) spaceheaps
A service reports a running count of handled requests once a minute. A faulty collector corrupts some readings, so the series goes up and down. A correct running count only goes up, and it goes up by at least one every minute.
You may replace any reading by any whole number, and the number can be negative. Changing a reading from x to y costs |x - y| units of error. Your team lead asks: "What is the least total change that makes the series strictly increasing?" A day can have 100,000 readings.
Write min_total_correction(readings).
readings[i] is the reading of minute i.|old - new| over all readings.0 when the readings already increase strictly.Input: readings = [6, 2, 9, 4, 5]
Output: 11Subtract the position from each reading, and the task becomes making the new numbers never decrease. A heap keeps the shifted numbers, with the largest on top:
| Minute | Reading | Shifted | Largest after the push | Gap paid | Total |
|---|---|---|---|---|---|
| 1 | 6 | 6 | 6 | 0 | 0 |
| 2 | 2 | 1 | 6 | 5 | 5 |
| 3 | 9 | 7 | 7 | 0 | 5 |
| 4 | 4 | 1 | 7 | 6 | 11 |
| 5 | 5 | 1 | 1 | 0 | 11 |
One best series is 1, 2, 3, 4, 5. It costs 5 + 0 + 6 + 0 + 0 = 11.
Input: readings = [1, 2, 3]
Output: 0The readings already increase strictly.
Input: readings = [3, 2, 1]
Output: 4The series 1, 2, 3 costs 2 + 0 + 2 = 4, and no strictly increasing series costs less.
1 ≤ len(readings) ≤ 100,0000 ≤ readings[i] ≤ 1,000,000,000A table with one entry for each reading and each possible final value has up to 100,000 × 100,000 entries, which is 10 billion. Even with only the values that occur, the work is quadratic. The table must be kept in a much smaller form.