1500. Best Average Stretch
An analyst tracks daily returns in nums and wants the best average over a streak of at least k consecutive days. Return the maximum average of any contiguous subarray whose length is at least k, as a double; answers within 1e-5 absolute or relative error are accepted.
Binary search the average a: it is achievable exactly when some window of length at least k has a sum of (nums[i] - a) that is non-negative, which prefix sums and a running minimum of earlier prefixes can test in one pass. Run enough iterations for the precision required. Target O(n log(range / precision)) time and O(n) extra space.
Example 1
- Input:
- nums = [1,12,-5,-6,50,3], k = 4
- Output:
- 12.750000000000002
- Explanation:
The window [12, -5, -6, 50] sums to 51 over 4 days, an average of 12.75.
Example 2
- Input:
- nums = [5], k = 1
- Output:
- 5
- Explanation:
The only window is [5], with average 5.
Example 3
- Input:
- nums = [-3,-1,-2], k = 2
- Output:
- -1.5
- Explanation:
Of the windows of length 2 or more, [-1, -2] has the best average, -1.5.
Constraints
1 ≤ k ≤ n ≤ 104; -104 ≤ nums[i] ≤ 104; absolute or relative error 1e-5
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- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log(range / precision))
- Space
- O(n)