Skip to content
Veltoryx Technologies
FreeProblem 27● EasyLeetCode #643 ↗5 min readUpdated 30 October 2026

Maximum Average Subarray I

Find the contiguous subarray of fixed length k with the highest average using a sliding window running sum.

01The problem

You are given an integer array nums and an integer k. Find a contiguous subarray of length k that has the maximum average value, and return this value. Any answer with a calculation error less than 10⁻⁵ will be accepted.

InputOutputWhy
nums = [1, 12, -5, -6, 50, 3], k = 412.75Window [12, -5, -6, 50] has sum 51, 51 / 4 = 12.75
nums = [5], k = 15.0Single element window is 5.0
nums = [-1, -2, -3], k = 2-1.5Window [-1, -2] has sum -3, -3 / 2 = -1.5

Constraints: 1 ≤ k ≤ n ≤ 100,000, -10,000 ≤ nums[i] ≤ 10,000.

02How to spot it

  • A contiguous subarray of fixed length k is requested.
  • Finding the largest average across all windows of identical length k is equivalent to finding the maximum sum.
  • Neighboring windows share k - 1 elements, so each step can update the sum in O(1) by adding the incoming element and subtracting the outgoing element.

So: fixed-size sliding window.

03Pseudocode

text
sum = a[0] + ... + a[k-1]
best = sum
for i from k to n - 1:
  sum += a[i] - a[i - k]
  best = max(best, sum)
return best / k
  1. Compute the sum of the first k elements.
  2. Slide the window one element right: add the new arrival, drop the one that fell off the left.
  3. Track the maximum sum seen, and divide by k once at the end.

04Watch it work

Visualizer · step through the algorithmnums = [1,12,-5,-6,50,3], k = 4
10
121
-52
-63
504
35
LR

Compute the sum of the first 4 elements: 1 + 12 - 5 - 6 = 2.

Pseudocode

  1. sum = a[0] + ... + a[k-1]
  2. best = sum
  3. for i from k to n - 1:
  4. sum += a[i] - a[i - k]
  5. best = max(best, sum)
  6. return best / k

Variables

sum
2
k
4
step 1 / 7

05Step-by-step dry run

  1. 1
    10
    121
    -52
    -63
    504
    35
    LR

    Compute the sum of the first 4 elements: 1 + 12 - 5 - 6 = 2.

    sum = 2k = 4

  2. 2
    10
    121
    -52
    -63
    504
    35
    LR

    Initialize best = 2 with the first window sum.

    sum = 2best = 2

  3. 3
    10
    121
    -52
    -63
    504
    35
    LR

    Slide window right: add 50 (entering at index 4), drop 1 (leaving at index 0). New sum: 51.

    i = 4sum = 51best = 51

  4. 4
    10
    121
    -52
    -63
    504
    35
    LR

    Sum 51 beats previous best! Update best = 51. Window: [12, -5, -6, 50].

    sum = 51best = 51

  5. 5
    10
    121
    -52
    -63
    504
    35
    LR

    Slide window right: add 3 (entering at index 5), drop 12 (leaving at index 1). New sum: 42.

    i = 5sum = 42best = 51

  6. 6
    10
    121
    -52
    -63
    504
    35
    LR

    Sum 42 does not beat best 51. Best remains 51.

    sum = 42best = 51

  7. 7
    10
    121
    -52
    -63
    504
    35

    Maximum window sum is 51. Divide by k (4) to get the maximum average: 12.75.

    best = 51k = 4result = 12.75

06Java solution

MaxAverageSubarray.java
public class MaxAverageSubarray {
    public static double findMaxAverage(int[] nums, int k) {
        int sum = 0;
        for (int i = 0; i < k; i++) sum += nums[i]; // first window
        int best = sum;
        for (int i = k; i < nums.length; i++) {
            sum += nums[i] - nums[i - k]; // slide: add new, drop old
            best = Math.max(best, sum);
        }
        return (double) best / k;
    }

    public static void main(String[] args) {
        System.out.println(findMaxAverage(new int[]{1, 12, -5, -6, 50, 3}, 4));
        System.out.println(findMaxAverage(new int[]{5}, 1));
        System.out.println(findMaxAverage(new int[]{-1, -2, -3}, 2));
    }
}
Expected output
12.75
5.0
-1.5

Tricky lines, decoded

  • sum += nums[i] - nums[i - k]: Slides the window in O(1) arithmetic without summing k elements again.
  • (double) best / k: Cast to double before dividing, otherwise Java performs integer division and truncates decimal values.

07Why it works

Consecutive windows of length k overlap everywhere except at their boundaries: exactly one element leaves the left, and one enters the right. Adding the newcomer and subtracting the departed number produces the exact total of the new window in O(1). Because all windows have length k, maximizing the sum directly maximizes the average.

Invariant: Before checking the window ending at index i, sum equals the exact sum of nums[i - k + 1 .. i].

08Time and space

  • Time: O(n). A single pass computes the initial window and slides across the remaining n - k positions.
  • Space: O(1). Only two scalar variables (sum and best) are tracked.

09Edge cases

InputOutputWhy it matters
[5], k = 15.0Single element array (k = n = 1)
[-1, -2, -3], k = 2-1.5All-negative values
[0, 4, 0, 3, 2], k = 14.0k = 1 is just the maximum element
[7, 7, 7, 7], k = 47.0Entire array is the only window (k = n)
[-10000, 10000], k = 110000.0Large negative and positive values

10Common mistakes

  • Integer division. Writing best / k returns 12.0 instead of 12.75. Always cast (double) best / k.
  • Initializing best = 0. An all-negative array (like [-5], k = 1) would wrongly return 0.0. Initialize best = sum from the first window.
  • Dividing on every iteration. Calculating sum / (double) k inside the loop causes unnecessary floating-point division and precision drift. Compare integer sums and divide once at the end.

11Other approaches

ApproachTimeSpaceUse when
Re-sum each windowO(n · k)O(1)Only acceptable when k = 1 or tiny
Sliding sumO(n)O(1)Default interview solution
Prefix sumsO(n)O(n)Multiple static range queries

12In the interview

  • Streaming data? Maintain a queue of the last k values and a running sum. When an element arrives, enqueue it and dequeue the front element.
  • Why compare sums instead of averages? Because k is identical for every candidate, a larger sum always gives a larger average. Integer math avoids rounding mistakes.

13Check your understanding

Quiz · 2 questions

0 of 2 answered

  1. 1. Why do we initialize best with the sum of the first window instead of 0?

  2. 2. Why is it better to compare sums inside the loop and divide by k only at the end?

14Solve it yourself

Try it on LeetCode #643.