Opening the reading…
Opening the reading…
SLIDING WINDOW › FIXED SIZE SLIDING-WINDOW
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Every candidate has exactly k elements, so its average is its sum divided by the same positive number k. That means the window with the largest average is exactly the window with the largest sum. The problem therefore becomes: inspect every contiguous block of length k and keep the greatest sum.
Adjacent windows overlap in k - 1 positions. When the window moves one step right, only two values change: the old leftmost value leaves and the new rightmost value enters. Reusing the previous sum gives the next sum in constant time, and dividing only the final maximum by k avoids unnecessary floating-point work.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The first window uses k additions, and each of the remaining n - k windows uses one addition, one subtraction, and one comparison. Each array element enters and leaves the running window at most once, so no window is rescanned. |
| Space | O(1) extra | Only the current sum, the best sum, and loop variables are stored. The returned average is one scalar of required output, so it is excluded from working space; the bound stays O(1) for every input shape. |
#include <vector>
using namespace std;
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int sum = 0;
for (int i = 0; i < k; ++i) {
sum += nums[i];
}
int maxSum = sum;
for (int i = k; i < static_cast<int>(nums.size()); ++i) {
sum += nums[i] - nums[i - k];
if (sum > maxSum) {
maxSum = sum;
}
}
return static_cast<double>(maxSum) / k;
}
};The initialization of maxSum is part of the algorithm, not bookkeeping. The first window is a valid candidate before the loop begins, so it supplies a real baseline. This matters when every value is negative: starting maxSum at zero would make an impossible empty choice look better than every legal window.
The cast in the return statement controls the division type. Without converting maxSum to double first, integer division would discard the fractional part before the result is returned. Casting only after division cannot restore that lost precision.