1307. Best Average Stretch Range

An analyst has n daily scores in the array nums and wants the best average over a run of consecutive days whose length is at least minLen and at most maxLen. Return the largest such average as a floating-point number; answers within an absolute or relative error of 1e-5 are accepted. Binary search on the answer x: x is reachable exactly when some allowed run has a non-negative sum after subtracting x from every score, and a prefix-sum array with a sliding-window minimum deque tests that in linear time. Target O(n log(R / e)) time for score range R and precision e, with O(n) space.

Example 1

Input:
nums = [4,-2,6,1,-3,5], minLen = 2, maxLen = 3
Output:
3.5
Explanation:

The run [6, 1] has length 2 and average 3.5, which beats every other allowed run of two or three scores.

Example 2

Input:
nums = [5,5,5], minLen = 1, maxLen = 3
Output:
5
Explanation:

Every score is 5, so any allowed run averages exactly 5.0.

Example 3

Input:
nums = [-4,-1,-9], minLen = 2, maxLen = 2
Output:
-2.5
Explanation:

Runs must have exactly 2 scores: [-4, -1] averages -2.5 and [-1, -9] averages -5, so the answer is -2.5.

Constraints

1 ≤ minLen ≤ maxLen ≤ n ≤ 1000

-104 ≤ nums[i] ≤ 104

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-5: |answer - expected| <= 1.0E-5 x max(1, |expected|).
Tolerance
0.00001

Expected complexity

Time
O(n log(R / e))
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…