DSA
Maximum Average Subarray I
Sliding Window - Fixed approach. Optimal — Time O(n), Space O(1).
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.
Sliding Window - Fixed#
Since every subarray has the same length k, maximizing the average is equivalent to maximizing the sum — we only need to track sums, not averages during the scan. Compute the sum of the first window of size k as a starting point, then slide the window one position at a time: add the incoming element on the right and subtract the outgoing element on the left. This keeps the running sum updated in O(1) per step without re-summing the entire window. Track the maximum sum seen across all windows and divide by k at the end to produce the maximum average.
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int n = nums.size();
int sum = 0;
for(int i=0;i<k;i++)
sum += nums[i];
int maxSum = sum;
for(int i=k; i<n;i++){
sum += nums[i];
sum -= nums[i-k];
maxSum = max(sum, maxSum);
}
return (double)maxSum/k;
}
};
Time Complexity: O(n)
Space Complexity: O(1)