KatInterview

Quickest Kilometer Within a Run Recorded in 5-Second Splits

Arrays & HashingAuto-graded · 25 test cases
MediumAuto-gradedArrays & Hashingprefix-sumsbinary-searchsliding-window

Last updated

Find the highest average speed over any 1000 m stretch of a run given per-5-second distances, using prefix sums, binary search and interpolation at boundaries.

A fitness tracker logs a run as a list of non-negative integers splits. Entry splits[i] is the number of meters covered during the i-th 5-second slot, which spans seconds 5*i to 5*i + 5.

Your task is to find the runner's best kilometer: the highest average speed (in meters per second) achieved over any continuous span of time in which exactly 1000 meters are covered.

Motion model

Within a single slot the runner moves at a constant speed. After t seconds of slot i (where 0 <= t <= 5), the runner has covered splits[i] * t / 5 meters of that slot. A span may therefore start or end part-way through a slot.

Rules

  • A valid span is a time range [a, b] with 0 <= a < b <= 5 * len(splits) in which exactly 1000 meters are covered under the model above.
  • The average speed of a span is 1000 / (b - a). Slots with 0 meters that fall inside a span still contribute their full time to b - a.
  • A span may lie entirely inside one slot if that slot alone covers at least 1000 meters.
  • Return the maximum average speed over all valid spans. This is the same as finding the span with the smallest duration.
  • Your answer is accepted if its relative error from the exact optimum is at most 1% (0.01).

Constraints

  • 1 <= len(splits) <= 10^5
  • 0 <= splits[i] <= 10^5
  • sum(splits) >= 1000, so at least one valid span always exists.
  • sum(splits) can reach 10^10, which is larger than a 32-bit integer. Use 64-bit or arbitrary-precision totals.

Examples

Example 1

Input: best_kilometer_speed([200, 200, 200, 200, 200])

Output: 40

Example 2

Input: best_kilometer_speed([100, 400, 400, 300])

Output: 75

Example 3

Input: best_kilometer_speed([1500])

Output: 300

Hints

Hint 1

Switch from thinking in time to thinking in distance. Build prefix sums so you can ask at what time the runner had covered a given total distance.

Hint 2

If you fix the distance at which a span starts, its end distance is that plus 1000, so the duration is a function of the start distance. This function is piecewise linear, and its breakpoints are where the start or the end lands on an interval boundary.

Hint 3

A piecewise linear function reaches its minimum at a breakpoint, so only spans that start on a slot boundary or end on a slot boundary need checking. Binary search the prefix sums to find the slot containing the other end, and interpolate inside it.