#643

Maximum Average Subarray I

Easy Fixed window

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Find the contiguous subarray of length k with the largest average and return that average.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the best average of any k neighbours in a row.

Why this works: k is fixed, so best average = best sum ÷ k. Slide: add the new number, subtract the one that left.

Example: [1, 12, -5, -6, 50, 3], k = 4

first window 1+12-5-6 = 2slide: +50 -1 = 51slide: +3 -12 = 42best 51 → 12.75

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Re-summing all k elements for every window — O(n·k).

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Sliding Window
🎬 Episode 10: video coming soon