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
Understanding the Visualization
1
Input
Array [1,12,-5,-6,50,3] and k=4
2
Process
Find all subarrays length ≥ 4 and calculate averages
3
Output
Return maximum average found: 12.75
Key Takeaway
🎯 Key Insight: Binary search on the answer space is more efficient than checking all subarrays directly
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code