sagelearnai

Maximum Average Subarray I

Difficulty: Easy · Pattern: Sliding Window · LeetCode #643

Find the contiguous subarray of length exactly k with the maximum average, and return that average.

Examples

text
nums = [1, 12, -5, -6, 50, 3], k = 4  →  12.75    ((12 − 5 − 6 + 50) / 4)
nums = [5], k = 1                     →  5

Hints

  1. Recomputing each window's sum costs O(k).
  2. Slide: add the entering element, subtract the leaving one.

Approach

Sum the first k elements, then slide the window one step at a time: sum += nums[i] − nums[i − k]. Track the maximum sum and divide by k at the end. O(n).

Complexity

Time: O(n). Space: O(1).

Python solution
def findMaxAverage(nums, k):
    s = best = sum(nums[:k])
    for i in range(k, len(nums)):
        s += nums[i] - nums[i - k]
        best = max(best, s)
    return best / k
JavaScript solution
function findMaxAverage(nums, k) {
  let s = 0;
  for (let i = 0; i < k; i++) s += nums[i];
  let best = s;
  for (let i = k; i < nums.length; i++) { s += nums[i] - nums[i - k]; best = Math.max(best, s); }
  return best / k;
}