Music streaming app~40 min2s · 256 MBtarget O(n) time, O(n) spacesliding-window-variable · monotonic-deque
A video editing app measures the brightness of every frame of a video, as one number per frame. A steady clip is a stretch of consecutive frames where the brightest and the darkest frame differ by at most a tolerance. Steady clips make good previews, because nothing flickers.
The editor wants to know how many steady clips the video offers. Two clips with different first or last frames are different clips, even when one contains the other.
Write count_steady_clips(brightness, tolerance).
brightness[i] is the brightness of frame i.l to r, with l <= r. It is steady when the largest brightness in the range minus the smallest is at most tolerance.Input: brightness = [3, 5, 4, 9, 8, 7], tolerance = 2
Output: 12The trace moves a window along the frames. For each end frame, it keeps the leftmost start that still gives a steady clip.
| End frame | Brightness | Window of steady starts | Largest and smallest | Clips ending here | Total |
|---|---|---|---|---|---|
| 0 | 3 | 3 | 3 and 3 | 1 | 1 |
| 1 | 5 | 3, 5 | 5 and 3 | 2 | 3 |
| 2 | 4 | 3, 5, 4 | 5 and 3 | 3 | 6 |
| 3 | 9 | 9 | 9 and 9 | 1 | 7 |
| 4 | 8 | 9, 8 | 9 and 8 | 2 | 9 |
| 5 | 7 | 9, 8, 7 | 9 and 7 | 3 | 12 |
The output is 12. At frame 3, the window shrinks to the frame alone, because 9 is far from every earlier frame.
Input: brightness = [1, 2, 3, 4], tolerance = 1
Output: 7Neighbouring frames differ by 1, but the range of 3 frames differs by 2. So the 4 single frames and the 3 pairs are steady, and the other 3 clips are not.
Input: brightness = [6, 6, 6], tolerance = 0
Output: 6With tolerance 0 and equal frames, every clip is steady: 3 + 2 + 1 = 6.
1 ≤ brightness.length ≤ 100,000 (frames)0 ≤ brightness[i] ≤ 1,000,000 (brightness)0 ≤ tolerance ≤ 1,000,000Checking every clip costs about n × n / 2 steps, about 5 × 10^9. The answer itself can be that large, 5 × 10^9 when every clip is steady, so it needs a 64-bit integer.
A window grows on the right and shrinks on the left. Two queues keep its largest and smallest values. That gives the count in about n steps.