Maximum Average Subarray I - 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 exactly k that has the maximum average value.
Think of it like finding the best performing streak in a series of scores! For example, if you have test scores [1, 12, -5, -6, 50, 3] and want to find the best 4 consecutive scores, you'd calculate averages for each possible group of 4 and return the highest one.
Goal: Return the maximum average value as a floating-point number.
Note: 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:
Maximum average subarray is [12,-5,-6,50] with sum 51 and average 51/4 = 12.75
example_2.py โ Single Element
$
Input:
nums = [5], k = 1
โบ
Output:
5.00000
๐ก Note:
Only one subarray possible: [5] with average 5.0
example_3.py โ All Negative
$
Input:
nums = [-1,-2,-3,-4], k = 2
โบ
Output:
-1.50000
๐ก Note:
Maximum average subarray is [-1,-2] with sum -3 and average -3/2 = -1.5
Constraints
- n == nums.length
- 1 โค k โค n โค 105
- -104 โค nums[i] โค 104
- k is always valid (k โค length of array)
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Window
Calculate sum of first k elements to establish our baseline
2
Slide and Update
Move window right: subtract outgoing element, add incoming element
3
Track Maximum
Keep track of the highest sum encountered during sliding
4
Return Average
Divide the maximum sum by k to get the maximum average
Key Takeaway
๐ฏ Key Insight: The sliding window technique transforms an O(n*k) problem into O(n) by maintaining a running sum and updating it incrementally rather than recalculating from scratch.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code