Code Logo

Maximum Average of K Consecutive

Published at24 Jul 2026
Easy 4 views
Like0

Find the maximum average of any k consecutive elements as a float.

Use a sliding window of size k. Initialize the window state with the first k elements. Slide the window one position at a time, updating the state efficiently. Track the maximum average across all windows.

The sliding window technique processes each element exactly twice (once when it enters, once when it leaves), giving O(n) time complexity with O(1) extra space.

Edge cases include empty arrays (return appropriate default like 0), k larger than array length (return default), and single-element arrays where k=1.

Compute the sum of each k-length window, then divide by k to get the average. Track the maximum average. The sliding window maintains the running sum.

Example Input & Output

Example 1
Input
[],2
Output
0.0
Example 2
Input
[10,20,30],2
Output
25.0
Example 3
Input
[5],1
Output
5.0
Example 4
Input
[-1,0,1],2
Output
0.5
Example 5
Input
[1,2,3,4,5],3
Output
4.0

Algorithm Flow

Recommendation Algorithm Flow for Maximum Average of K Consecutive
Recommendation Algorithm Flow for Maximum Average of K Consecutive

Solution Approach

Initialize the sliding window with the first k elements. Compute the initial maximum average. For each position i from k to n-1, update the window by removing element i-k and adding element i. Update the result if the new window value is better.

Best Answers

java
class Solution {
    public int solution(int[] nums, int k) {
        return 0;
    }
}