Maximum Average Subarray I

EasySliding Window · Fixed Size🧩 Sliding WindowLeetCode #643 ↗Updated

Problem

Given an integer array nums and a window length k, look at every contiguous block of exactly k elements and return the largest average among them. Answers within 10-5 of the true value are accepted.
Inputnums = [1,12,-5,-6,50,3], k = 4Output12.75 (block [12,-5,-6,50])
Inputnums = [5], k = 1Output5.0

1 ≤ k ≤ n ≤ 105  ·  -104 ≤ nums[i] ≤ 104

Try it yourself

Java
class Solution {
    public double findMaxAverage(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
All windows have the same length k, so maximising the average is the same as maximising the sum. Neighbouring windows share k - 1 elements: add the newcomer, subtract the one that falls off.
PatternSliding Window

Instinct Longest, shortest or count of contiguous subarrays/substrings meeting a rule? Grow a window on the right, shrink it on the left, never step back.

Memory hack Move like a caterpillar - the head stretches forward to grab, the tail pulls up only when the body breaks the rule.

Open the Sliding Window guide →

Approaches

Brute ForceSum Every Window

Time O(n · k)Space O(1)

For each start i from 0 to n - k, add up the k elements from scratch and keep the biggest total. Divide by k once at the end.

Java
public double findMaxAverage(int[] nums, int k) {
    int best = Integer.MIN_VALUE;
    for (int i = 0; i + k <= nums.length; i++) {
        int sum = 0;
        for (int j = i; j < i + k; j++) sum += nums[j];
        best = Math.max(best, sum);
    }
    return (double) best / k;
}

Direct, but recomputes overlapping sums — O(n·k) blows up when k ≈ n/2.

At a glance

LevelApproachTimeSpace
Brute ForceSum Every WindowO(n · k)O(1)
BetterPrefix SumsO(n)O(n)
OptimalFixed-Size Sliding WindowO(n)O(1)
Common pitfalls
  • Starting best at 0 — wrong when every number is negative.
  • Integer division: cast to double before dividing by k.
  • Off-by-one on the last window: the final start index is n - k.
Interview tips
  • Note that equal window sizes let you compare sums instead of averages.
  • Check overflow: |sum| ≤ 105 · 104 = 109 fits in an int.
  • Name it a fixed-size window to contrast with variable windows.
Pattern
Fixed-size sliding window → aggregate (sum/count) over every block of exactly k consecutive elements.
My notes saved in this browser