KatInterview

Max Speed Continuous Window on Ticked Rate Stream

Greedy & IntervalsAuto-graded · 20 test cases
MediumAuto-gradedGreedy & Intervalssliding-windowtwo-pointersgreedy

Last updated

Find the maximum average throughput over a continuous time window of a specified size, given rate logs over uniform time ticks.

An automated logging system measures production output over consecutive time intervals of uniform duration tick_seconds. The list ticks contains non-negative integers where ticks[i] represents the total count of items produced during the $i$-th tick.

Within any single tick, production is assumed to occur at a constant uniform rate. Thus, if $t$ seconds have elapsed into tick $i$ (where $0 \le t \le \text{tick_seconds}$), exactly $\text{ticks}[i] \times \frac{t}{\text{tick_seconds}}$ items have been processed in that tick.

Your objective is to find a continuous time window during which exactly target_units items were produced such that the average speed (items per second) during that window is maximized.

A valid window can start and end at any fractional second across the total duration. The average speed of a window of duration $D$ seconds is $\frac{\text{target_units}}{D}$. Minimizing the duration $D$ maximizes the average speed.

Constraints

  • 1 <= len(ticks) <= 10^5
  • 1 <= tick_seconds <= 60
  • 0 <= ticks[i] <= 10^5
  • sum(ticks) >= target_units
  • 1 <= target_units <= 10^9

Examples

Example 1

Input: fastest_stretch_speed([200, 200, 200, 200, 200], 4, 1000)

Output: 50

Example 2

Input: fastest_stretch_speed([33, 46, 4], 2, 52)

Output: 22.000000000000004

Hints

Hint 1

Minimizing the window's total duration for a fixed target output maximizes the average speed.

Hint 2

Continuous rate changes only occur at tick boundaries. Consider how moving a window's start/end points affects duration when the entry rate differs from the exit rate.

Hint 3

An optimal window will always have at least one of its endpoints aligned with a tick boundary, unless the target output is completed entirely within a single tick.