Maximum Average Subarray II - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
💡 Note: Maximum average subarray is [12,-5,-6,50] with sum 51 and length 4, giving average 51/4 = 12.75
Example 2 — Minimum Length
$ Input: nums = [5], k = 1
Output: 5.00000
💡 Note: Only one element, so the subarray [5] has average 5.0
Example 3 — All Negative
$ Input: nums = [-1,-2,-3,-4], k = 2
Output: -1.50000
💡 Note: Best subarray is [-1,-2] with average (-1-2)/2 = -1.5

Constraints

  • n == nums.length
  • 1 ≤ k ≤ n ≤ 104
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Maximum Average Subarray II INPUT nums array: 1 i=0 12 i=1 -5 i=2 -6 i=3 50 i=4 3 i=5 Parameters: n = 6, k = 4 min subarray len = 4 Binary Search Range: min(nums) = -6 max(nums) = 50 Find max avg of subarray with length >= k Error tolerance: 10^-5 ALGORITHM STEPS 1 Binary Search on Answer Search avg in [min, max] mid = (lo + hi) / 2 2 Transform Array Subtract mid from each elem b[i] = nums[i] - mid 3 Prefix Sum Check Check if subarray sum >= 0 with len >= k exists 4 Update Search Bounds If valid: lo = mid Else: hi = mid Binary Search Iterations: lo=-6, hi=50, mid=22 lo=-6, hi=22, mid=8 lo=8, hi=22, mid=15 lo=8, hi=15, mid=11.5 ... lo=12.75, hi=12.75 FINAL RESULT Optimal Subarray Found: 12 -5 -6 50 indices [1, 4], length = 4 Calculation: Sum = 12+(-5)+(-6)+50 Sum = 51 Avg = 51 / 4 = 12.75 OUTPUT 12.75000 Verification: OK Max avg for len >= 4 No better subarray exists Key Insight: Binary search on the answer value! If we can check whether a valid subarray with average >= mid exists, we can binary search the maximum average. Transform: subtract mid from all elements, then find if any subarray of length >= k has non-negative sum. Use prefix sums with minimum prefix tracking for O(n) check. TutorialsPoint - Maximum Average Subarray II | Binary Search + Prefix Sum Approach
Asked in
Google 35 Facebook 28 Amazon 22
78.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen