Total Latency Spread Across All Monitoring Windows
Imagine you are on call for a backend service that logs request latency every second. For any contiguous monitoring window you care about its jitter, which you define as the spread inside that window: the maximum latency minus the minimum latency. A perfectly steady window has spread zero, a jittery window has large spread.
For a daily health audit you need the total spread summed across every possible contiguous window. This total is a single number that summarizes how unstable the service was during the day: each window contributes its own max minus min, and you add all contributions.
Formally, given an array latencies where latencies[i] is the latency at second i, for each subarray latencies[l..r] compute max(latencies[l..r]) - min(latencies[l..r]) and return the sum over all l <= r. A subarray of length one contributes zero because its max and min are equal.
I approach it this way: instead of enumerating all O(n^2) windows and scanning each for its max and min, I ask how much each individual measurement contributes as a maximum and as a minimum. If I can count for each position how many windows it dominates as the maximum and how many it dominates as the minimum, the whole total becomes a sum of contributions. That counting is exactly what a monotonic stack does efficiently.
Total Latency Spread Across All Monitoring Windows
Imagine you are on call for a backend service that logs request latency every second. For any contiguous monitoring window you care about its jitter, which you define as the spread inside that window: the maximum latency minus the minimum latency. A perfectly steady window has spread zero, a jittery window has large spread.