AAlgoLoopSpaced repetition for LeetCode
EASYSliding WindowLeetCode ↗

Maximum Average Subarray I

The key idea

Every length-k subarray shares k-1 elements with its neighbor. Instead of re-summing each window, slide a fixed-size window: add the new element entering on the right and subtract the element leaving on the left. Track the maximum window sum, then divide by k once at the end.

Problem

You are given an integer array nums consisting of n elements, and an integer k.

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10^-5 will be accepted.

Constraints

Examples

Input: nums = [1,12,-5,-6,50,3], k = 4 Output: 12.75000
Input: nums = [5], k = 1 Output: 5.00000

Complexity

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

See the full solution

410310
Step-by-step visualization
Start free →

More Sliding Window problems