The Maximum Average Subarray II problem is the advanced version of Part I. You are given an array of integers and an integer k. This time, you must find a contiguous subarray whose length is greater than or equal to k that has the maximum average value. You must return this maximum average with an acceptable error margin of .
This is a Hard-level problem that completely breaks the standard sliding window approach because the window size is variable (). Interviewers ask it to test a candidate's mastery of Binary Search on the Answer. It evaluates whether you can combine floating-point binary search with Prefix Sum math to validate an abstract statistical guess in time.
This problem leverages Binary Search on the Answer and Prefix Sums.
low = min(array), high = max(array).mid.mid is possible for a length , we subtract mid from every element in the array. Now, we just need to find any subarray of length that has a sum .i, we subtract the minimum prefix sum seen so far (from index to ). If this difference is , the guess mid is valid! Adjust low = mid. Else high = mid.Array: [1, 12, -5, -6, 50, 3], k = 4.
Guess mid = 10. Subtract 10 from all elements.
Shifted: [-9, 2, -15, -16, 40, -7].
We need a subarray length 4 with sum .
Prefix sums:
min_prev_sum tracks prefix at i-k. min_prev_sum = 0.min_prev_sum updates with prefix at idx 0 (-9). min_prev_sum = -9.
Current prefix is 2. Best subarray ending here has sum 2 - (-9) = 11. !
We found a subarray of length 5 [12, -5, -6, 50] whose average is . We can search higher.A major pitfall is trying to track all possible window sizes using nested loops, which results in and a Time Limit Exceeded error. Another mistake is in the binary search loop condition. Because we are searching for a double, using while (low <= high) will cause an infinite loop due to floating-point precision. You must use an error margin like while (high - low > 1e-5) to terminate correctly.
The key to the Maximum Average Subarray II coding problem is the mathematical shift. If you want to know if an array A has an average , it is mathematically identical to checking if sum(A[i] - M) >= 0. This brilliantly removes division from the inner loop, turning an average problem into a much simpler prefix-sum problem.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Zero Array Transformation II | Medium | Solve | |
| Special Array II | Medium | Solve | |
| Count Subarrays With Score Less Than K | Hard | Solve | |
| Maximum Fruits Harvested After at Most K Steps | Hard | Solve | |
| Minimum Space Wasted From Packaging | Hard | Solve |