Maximum Average Subarray I - Problem
You are given an integer array nums consisting of n elements, and an integer k.
Find a contiguous subarray whose length is 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 average 51/4 = 12.75
Example 2 — Small Array
$
Input:
nums = [5], k = 1
›
Output:
5.00000
💡 Note:
Only one element, so maximum average is 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 -3/2 = -1.5
Constraints
- n == nums.length
- 1 ≤ k ≤ n ≤ 105
- -104 ≤ nums[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums and window size k
2
Process
Find all subarrays of length k and calculate averages
3
Output
Return maximum average found
Key Takeaway
🎯 Key Insight: Use sliding window to avoid recalculating the entire sum for each window - just add the new element and subtract the old one
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code