Maximum Average Subarray - I
Problem Link
Maximum Average Subarray I – LeetCode #643
Problem Statement
You are given an integer array nums containing n elements, and an integer k.
Your task is to find the contiguous subarray of length k that has the maximum average value, and return this average as a double.
Any returned result with an error less than 10⁻⁵ is considered correct.
Examples
-
Input:
nums = [1,12,-5,-6,50,3],k = 4
Output:12.75000
Explanation: Subarray[12, -5, -6, 50]has sum51, so average =51 / 4 = 12.75. -
Input:
nums = [5],k = 1
Output:5.00000
Constraints
-
1 <= k <= n <= 10⁵ -
-10⁴ <= nums[i] <= 10⁴
Intuition
This is a direct variation of the Maximum Sum Subarray of Size K problem.
The only difference is that we need to return the average instead of the sum.
We can still use the Fixed Size Sliding Window technique, where we:
-
Compute the sum of the first
kelements -
Slide the window one element at a time while updating the sum
-
Keep track of the maximum sum, and finally return
maxSum / k
This approach allows us to process the entire array in linear time.
Approach
-
Initialize a variable
sumto hold the sum of the firstkelements. -
Store
suminmaxSum. -
From index
kton-1, slide the window:-
Add the new element at
i -
Subtract the element going out of the window at
i-k -
Update
maxSumif the newsumis greater
-
-
Return
maxSum / kas a floating-point result
Java Code
class Solution {
public double findMaxAverage(int[] nums, int k) {
int sum = 0;
// Step 1: Compute the initial window sum
for (int i = 0; i < k; i++) {
sum += nums[i];
}
int maxSum = sum;
// Step 2: Slide the window and update maxSum
for (int i = k; i < nums.length; i++) {
sum += nums[i] - nums[i - k];
maxSum = Math.max(maxSum, sum);
}
// Step 3: Return the average
return (double) maxSum / k;
}
}
Time and Space Complexity
-
Time Complexity:
O(n)
We traverse the array exactly once. -
Space Complexity:
O(1)
Only variables for tracking sum and max are used. No extra space is required.
Dry Run
Input:
nums = [1, 12, -5, -6, 50, 3], k = 4
Steps:
-
Initial window sum =
1 + 12 + (-5) + (-6) = 2,maxSum = 2 -
Slide window:
-
Add
50, remove1: sum =2 + 50 - 1 = 51,maxSum = 51 -
Add
3, remove12: sum =51 + 3 - 12 = 42,maxSum = 51
-
-
Final result =
51 / 4 = 12.75
Output: 12.75
Conclusion
This problem is another classic application of the Fixed Size Sliding Window technique.
The key idea is that, since the window size is fixed, we can maintain the sum of the window in constant time as we slide across the array. This allows us to compute the maximum average in O(n) time, making it scalable for large arrays (up to 10⁵ elements).
This approach generalizes well for:
-
Maximum/minimum averages
-
Comparing fixed-length windows
-
Handling real-time data streams