Maximum Average Subarray II - Problem

You are given an integer array nums consisting of n elements and an integer k. Your task is to find a contiguous subarray whose length is greater than or equal to k that has the maximum average value.

Unlike the simpler version where the subarray length is fixed, this problem allows variable-length subarrays (as long as they're at least k elements long). This makes it significantly more challenging because you need to consider all possible subarray lengths from k to n.

Example: Given nums = [1,12,-5,-6,50,3] and k = 4, you need to find the subarray of length โ‰ฅ 4 with the highest average. The subarray [12,-5,-6,50] has average 12.75, which turns out to be optimal.

Return the maximum average value as a double. Any answer within 10-5 of the actual answer will be accepted.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1,12,-5,-6,50,3], k = 4
โ€บ Output: 12.75000
๐Ÿ’ก Note: The subarray [12,-5,-6,50] has length 4 and average (12-5-6+50)/4 = 51/4 = 12.75, which is the maximum possible.
example_2.py โ€” Minimum Length
$ Input: nums = [5], k = 1
โ€บ Output: 5.00000
๐Ÿ’ก Note: Only one element, so the subarray is [5] with average 5.0.
example_3.py โ€” All Negative
$ Input: nums = [-1,-2,-3,-4,-5], k = 2
โ€บ Output: -1.50000
๐Ÿ’ก Note: The best subarray is [-1,-2] with length 2 and average (-1-2)/2 = -1.5.

Constraints

  • n == nums.length
  • 1 โ‰ค k โ‰ค n โ‰ค 105
  • -104 โ‰ค nums[i] โ‰ค 104
  • Answer precision: Any answer within 10-5 of the actual answer will be accepted

Visualization

Tap to expand
Maximum Average Subarray II: Binary Search Strategy112-5503k = 4 (minimum length)Binary Search Process:Search Space: [-6, 50]Not AchievableAchievablemid = 22Feasibility Check for mid = 12.75:Transform: [1-12.75, 12-12.75, -5-12.75, 50-12.75, 3-12.75] = [-11.75, -0.75, -17.75, 37.25, -9.75]โœ“ Subarray [-0.75, -17.75, 37.25] has sum 18.75 โ‰ฅ 0โœ“ Length = 3 โ‰ฅ k = 4? No, but subarray [1,2,3,4] works!Answer: 12.75 (maximum achievable average)
Understanding the Visualization
1
Set Search Bounds
Initialize left=min(nums) and right=max(nums) as possible average range
2
Binary Search Loop
For each mid value, check if there exists a valid subarray with average โ‰ฅ mid
3
Feasibility Check
Transform array by subtracting target, then find subarray with sum โ‰ฅ 0
4
Update Bounds
If feasible, search higher; otherwise search lower
5
Converge to Answer
Continue until bounds converge to maximum achievable average
Key Takeaway
๐ŸŽฏ Key Insight: By binary searching on the answer and using prefix sums for feasibility checks, we transform an O(nยณ) problem into an elegant O(n log(range)) solution.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
34.5K Views
Medium Frequency
~25 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