AlgoInsight

DSA problem

Maximum Average Subarray I

EasySliding Window - Fixed SizePattern: Fixed-Size Sliding Windowtop300AmazonGoogleMicrosoft

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.

The average of a subarray is the sum of its elements divided by its length k. Because every candidate window has the exact same length, maximizing the average is equivalent to maximizing the window sum. A brute-force scan of every window is wasteful since adjacent windows overlap heavily — the sliding window technique reuses that overlap to achieve linear time.

Examples

Example 1
Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75.
Example 2
Input: nums = [5], k = 1
Output: 5.00000
Explanation: The only subarray of length 1 is [5], with average 5.0.
Example 3
Input: nums = [0,4,0,3,2], k = 1
Output: 4.00000
Explanation: The best single element is 4, so the maximum average is 4.0.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

sliding-windowarray

Browse all DSA problems