Problem Description
Given an integer array nums and an integer k, find a contiguous subarray with length at least k that has the maximum average value and return this maximum average. The answer is accepted within a precision error of less than 10⁻⁵.
Key Insights
- Use binary search on the possible average values rather than on indices.
- Transform the problem by subtracting the candidate average from each element.
- Use prefix sum and the minimum prefix sum seen so far to check if a subarray of length at least k has a non-negative sum, indicating that the candidate average is achievable.
- Narrow the search range until the required precision is met.
Space and Time Complexity
Time Complexity: O(n * log(max - min) / precision)
Space Complexity: O(n)
Solution
The solution uses binary search to "guess" the maximum average. For each candidate average, subtract it from each element to create a transformed array. Then, determine if there exists a subarray (of length at least k) in the transformed array with a non-negative sum. This is done using prefix sums along with tracking the minimum prefix sum encountered. If such a subarray exists, it means the candidate average is achievable, and you can adjust the binary search accordingly. This approach leverages prefix sum computations, which are O(n) per binary search iteration.