KatInterview

Peak Pace Over Tightest 1000-Meter Windows in Interval Logs

Arrays & HashingAuto-graded · 26 test cases
MediumAuto-gradedArrays & Hashingsliding-windowtwo-pointersprefix-sums

Last updated

Sliding-window problem: for each end index find the shortest suffix with at least 1000 meters, compute its average speed, and return the maximum across all end indices.

A fitness tracker logs how many meters a person moves in each consecutive 5-second tick. You receive a list segments, where segments[i] is the number of meters moved during tick i. Your task is to compute the highest average speed reached over a "tight kilometer" window, as defined below.

Definitions

  • A window is a contiguous block of ticks [l, r] with l <= r. Its distance is segments[l] + ... + segments[r] (meters) and its duration is 5 * (r - l + 1) seconds.
  • For every end tick r, the tight window for r is the shortest window [l, r] whose distance is at least 1000. Equivalently, it uses the largest possible l such that the distance is still at least 1000. If even [0, r] has distance below 1000, tick r has no tight window.
  • The speed of a window is its entire distance divided by its duration, in meters per second. If the distance exceeds 1000 meters, the whole amount still counts; do not trim or interpolate inside a tick.

Task

Return the maximum speed over the tight windows of all end ticks r that have one.

If the total of all segments is below 1000, no tight window exists, and you must return -1.0.

Only tight windows are considered. A longer window ending at the same r is never considered, even if its average would be higher.

Answers within an absolute or relative error of 1e-6 are accepted.

Constraints

  • 1 <= len(segments) <= 100000
  • 0 <= segments[i] <= 1000, all values are integers.
  • The sum of all segments is at most 100000000.
  • When a tight window exists, the answer is greater than 0 and at most 200.0.

Examples

Example 1

Input: peak_tight_km_speed([300, 400, 300, 200, 500, 400])

Output: 73.33333333333333

Example 2

Input: peak_tight_km_speed([250, 250, 250, 240])

Output: -1

Example 3

Input: peak_tight_km_speed([0, 600, 500, 0, 600])

Output: 110

Hints

Hint 1

For a fixed end r, you want the largest l such that the sum of segments[l..r] is still at least 1000. Only that single window matters for r.

Hint 2

All values are non-negative, so as r grows, the best l for r never moves left. This lets you keep one left pointer that only moves forward.

Hint 3

Maintain the running sum of the current window. For each r, while removing segments[l] still leaves a sum of at least 1000, remove it and advance l. Then compute sum / (5 * (r - l + 1)). Skip r while the prefix sum is still under 1000.