Apply a fixed-size sliding window to find the greatest average.
Use the editor below to find the best average among all contiguous windows of exactly k values.
Reuse the window sum
Update the current sum as the window slides. Initialize the maximum from a real window so arrays containing negative values work correctly.
Submit your implementation when it passes the examples.
Given an integer array nums and an integer k, find the contiguous subarray of exactly k elements with the greatest average.
Return that maximum average.
1 ≤ k ≤ nums.length ≤ 100,000-10,000 ≤ nums[i] ≤ 10,000Results appear here after a run.
Sum the first k values to create the initial window. For every later position, add the value entering on the right and subtract the value leaving on the left.
Track the greatest window sum and divide it by k once at the end.
function findMaxAverage(nums, k) {
let windowSum = 0;
for (let index = 0; index < k; index++) {
windowSum += nums[index];
}
let maximumSum = windowSum;
for (let right = k; right < nums.length; right++) {
windowSum += nums[right] - nums[right - k];
maximumSum = Math.max(maximumSum, windowSum);
}
return maximumSum / k;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | The first window is built once and each slide performs two arithmetic updates. |
| Auxiliary space | O(1) | Only the running and maximum sums are stored. |