Maximum Average Subarray I Solution
Given an integer array nums and an integer k, return the maximum average value of any contiguous subarray of length k.
Problem Statement
We need the contiguous subarray of exactly k elements whose average is largest. Because every candidate window has the same size, maximizing the average is the same as maximizing the sum. That makes this a classic fixed-size sliding window problem.
Brute Force โ Recompute Every Window
Try every window of length k. For each start index, sum the next k elements from scratch, compute its average, and track the best.
[i, i+k-1] is already known, then window [i+1, i+k] differs by only one outgoing and one incoming element. Recomputing all k numbers wastes work and leads to O(nยทk).
| Metric | Value |
|---|---|
| Time | O(n ยท k) |
| Space | O(1) |
Fixed-Size Sliding Window โ O(n)
Build the first window sum of size k. Then slide right one step at a time: add the new number entering the window and subtract the old number leaving it. Track the maximum window sum seen. Because k is fixed, the best average comes from the best sum.
k cups of water. When the tray moves one slot right, one cup falls off the left and one new cup is added on the right. You do not re-measure every cup on the tray โ you just subtract the old one and add the new one.
- Step 1: Sum the first
kelements. - Step 2: Set
bestSum = windowSum. - Step 3: For each next position:
windowSum += nums[right] - nums[right-k]. - Step 4: Update
bestSumafter each slide. - Step 5: Return
(double) bestSum / k.
- Because every window has the same size, you never need to compare averages during the scan. Comparing sums is enough.
- Divide by
konly once at the end.
Visual Walkthrough
Trace through nums = [1, 12, -5, -6, 50, 3], k = 4:
Code โ Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Recompute each window | O(n ยท k) | O(1) | Simple but repeats overlapping work |
| Sliding window โ optimal | O(n) | O(1) | Each slide updates sum in O(1) |
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| k = 1 | [4, -2, 9], k=1 | Answer is just the maximum single element โ 9. |
| k = n | [2, 3, 4], k=3 | Only one possible window โ average of whole array. |
| All negative | [-5, -2, -8], k=2 | Best answer can still be negative. Don't initialize best to 0. |
| Single element | [5], k=1 | Trivial fixed window. |
| Large values | [10000, ...] | Use a wide enough sum type in Java to stay safe. |
bestSum / k as integers, decimals are truncated. Cast before dividing: (double) bestSum / k.