These clues point to Sliding Window: Fixed Size: Keep a window of exactly k elements; add the element entering and remove the one leaving instead of recomputing.
Stuck? Take one hint at a time
Solution.java · starter
class Solution {
public double findMaxAverage(int[] nums, int k) {
return 0.0;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Track the window sum, slide one step at a time, keep the maximum sum, and divide by k at the end.
Approach 1
class Solution {
public double findMaxAverage(int[] nums, int k) {
int sum = 0;
for (int i = 0; i < k; i++) sum += nums[i];
int best = sum;
for (int right = k; right < nums.length; right++) {
sum += nums[right] - nums[right - k];
best = Math.max(best, sum);
}
return (double) best / k;
}
}
Verdict: Each element enters and leaves once.
Before you submit
Edge cases and common mistakes
Test these inputs
k = n (one window)
k = 1
All negative values
Mistakes people make
Integer division (best / k without casting).
Starting best at 0 (wrong when all sums are negative).