SystemTutor
About
Sign in
Loading course documentation…
SystemTutor

COURSES

  • Data Structures & Algorithms
  • CSS MasterclassNew course
  • System DesignNew course

PRACTICE

  • Algorithm practice
  • CSS practice

LEGAL

  • Privacy Policy
  • Terms of Service
  • About

© 2026 SystemTutor. All rights reserved.

Built with 🫶 by Shatlyk

Course Overview
Algorithm Patterns OverviewFrequency CountersTwo SumValid AnagramGroup AnagramsFrequency Counters and Hash-Map LookupTwo PointersValid PalindromeTwo Sum IIContainer With Most WaterTwo-Pointer ReasoningSliding WindowMaximum Average Subarray ILongest Substring Without Repeating CharactersMinimum Size Subarray SumSliding-Window Reasoning
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 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.

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
Explanation: The four consecutive values [12, -5, -6, 50] have the largest sum, 51. Their average is 51 ÷ 4 = 12.75.

Example 2:

Input: nums = [5], k = 1
Output: 5
Explanation: The only window contains 5, so its average is 5 ÷ 1 = 5.

Constraints

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

Test results

Results appear here after a run.

Solution

A width-three window changes from 2, 5, 1 to 5, 1, 3. Subtracting 2 and adding 3 updates its sum from 8 to 9.

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 each slide performs two arithmetic updates.
Auxiliary spaceO(1)Only the running and maximum sums are stored.

How is this practice?

Previous lessonSliding WindowNext lessonLongest Substring Without Repeating Characters
Edit on GitHubReport on GitHub
On this page
%

On this page

Try It YourselfSolutionBig O notation