Command Palette

Search for a command to run...

Problem 7.1 · Sliding WindowEasy

Maximum Average Subarray

What it teaches: The fixed window template: add the entering element, subtract the leaving one.

Practise it on judges as “Maximum Average Subarray I”.

The problem

Given nums and k, find the contiguous subarray of length exactly k with the maximum average, and return that average.

Example 1

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

(12 − 5 − 6 + 50) / 4 = 12.75.

Example 2

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

Constraints

  • 1 ≤ k ≤ n ≤ 10⁵
  • −10⁴ ≤ nums[i] ≤ 10⁴

Pattern clues in the wording

  • → Subarray of fixed length k
  • → Maximise a sum (average = sum / k)

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.

Test cases

#InputExpected
1
nums = [1,12,-5,-6,50,3]
k = 4
12.75
2
nums = [5]
k = 1
5

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Optimal: fixed sliding window

Time O(n) Space O(1)

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).

Interview

Follow-up questions

What if the length can be k or more?