Maximum Average Subarray II Problem
Description
LeetCode Problem 644.
You are given an integer array nums consisting of n elements, and an integer k.
Find a contiguous subarray whose length is greater than or equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10^-5 will be accepted.
Example 1:
Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
Explanation:
- When the length is 4, averages are [0.5, 12.75, 10.5] and the maximum average is 12.75
- When the length is 5, averages are [10.4, 10.8] and the maximum average is 10.8
- When the length is 6, averages are [9.16667] and the maximum average is 9.16667
The maximum average is when we choose a subarray of length 4 (i.e., the sub array [12, -5, -6, 50]) which has the max average 12.75, so we return 12.75
Note that we do not consider the subarrays of length < 4.
Example 2:
Input: nums = [5], k = 1
Output: 5.00000
Constraints:
n == nums.length1 <= k <= n <= 10^4-10^4 <= nums[i] <= 10^4
Solution
Approach: Binary Search on the Average
Trying every subarray of length at least k takes O(n2) time. Instead, binary search on the answer: we only need a fast way to answer the yes/no question "is there a subarray of length >= k whose average is at least v?".
That question has a neat reformulation. A subarray has average >= v exactly when its sum is >= v * length, which is the same as saying that the sum of (x - v) over its elements is >= 0. So subtract v from every number and ask: is there a subarray of length >= k with a non-negative sum?
With prefix sums P[i] of the shifted numbers, a subarray ending just before index i and having length at least k starts at some j <= i - k, and its sum is P[i] - P[j]. That is largest when P[j] is smallest, so scan i from k to n while keeping the minimum of P[0..i-k]. The answer is yes as soon as P[i] - min >= 0. This check is a single O(n) pass.
The answer lies between the smallest and the largest number in nums. If the check says yes for mid, the best average is at least mid, so move lo = mid; otherwise hi = mid. Stop when hi - lo is tiny. The problem accepts an error below 10^-5, so we stop at 10^-6 to stay safely inside it.
The case people miss is the "length at least k" part: the best subarray can be longer than k. With nums = [10, 0, 10] and k = 2, both windows of length 2 have average 5, but the whole array has average 6.66667. The prefix-minimum check covers every length >= k at once, because j may be any index up to i - k.
Complexity: O(n log(R / ε)) time, where R is the range of the values (at most 2 * 104) and ε = 10^-6, so about 35 passes over the array. O(1) extra space.
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
def reachable(v: float) -> bool:
"""Is there a subarray of length >= k with average >= v?"""
# Subtract v from every number: we need a subarray of length >= k with sum >= 0.
s = sum(nums[:k]) - k * v # sum of the first i numbers, minus v each
if s >= 0:
return True
prefix = lowest = 0.0 # prefix: sum up to i - k; lowest: its minimum so far
for i in range(k, len(nums)):
s += nums[i] - v
prefix += nums[i - k] - v
lowest = min(lowest, prefix)
if s - lowest >= 0:
return True
return False
lo, hi = min(nums), max(nums)
while hi - lo > 1e-6:
mid = (lo + hi) / 2
if reachable(mid):
lo = mid
else:
hi = mid
return lo