Engineered
Algorithm Patterns

Maximum Average Subarray I

Apply a fixed-size sliding window to find the greatest average.

Try It Yourself

Use the editor below to find the best average among all contiguous windows of exactly k values. Reuse the current window sum instead of adding every window again.

Submit your implementation when it passes the examples. Initialize the maximum from a real window so arrays containing negative values work correctly.

Maximum Average Subarray I

easySliding Window · Arrays20 minLC 643
Problem

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.

Example 1:

Input: nums = [1, 12, -5, -6, 50, 3], k = 4
Output: 12.75

Example 2:

Input: nums = [5], k = 1
Output: 5

Constraints

  • 1 ≤ k ≤ nums.length ≤ 100,000
  • -10,000 ≤ nums[i] ≤ 10,000
0 attempts

Solution

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;
}

Big O notation

MeasureComplexityExplanation
TimeO(n)The first window is built once and every remaining value enters and leaves once.
Auxiliary spaceO(1)Only the running and maximum sums are stored.

How is this lesson?