Code Logo

Maximum Average of K Consecutive

Published at24 Jul 2026
Easy 7 views
Like0

Given an array of integers and a window size k, find the maximum average value among all subarrays of length k. Return the maximum average as a floating-point number.

For example, in [1, 12, -5, -6, 50, 3] with k=4, windows: [1,12,-5,-6] avg=0.5, [12,-5,-6,50] avg=12.75, [-5,-6,50,3] avg=10.5. Maximum average is 12.75.

This is the maximum average subarray problem, a variation of the maximum sum subarray. It teaches converting between sum and average by dividing by k.

The solution uses a sliding window to track the sum, computes the average for each window, and returns the maximum average found.

Edge cases include k larger than the array (return 0), an empty array (return 0), and floating-point precision (division by k may produce non-integer results).

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

Solution Approach

Use a sliding window to maintain the sum incrementally and compute averages.

function maxAverage(arr, k)
  if k > length(arr) or length(arr) == 0 then return 0
  sum = 0
  for i = 0 to k - 1
    sum = sum + arr[i]
  maxAvg = sum / k
  for i = k to length(arr) - 1
    sum = sum - arr[i - k] + arr[i]
    avg = sum / k
    if avg > maxAvg then maxAvg = avg
  return maxAvg

Sum the first window and compute its average. Slide the window, update the sum, compute each new average, and track the maximum.

Time complexity is O(n), space complexity is O(1).

Best Answers

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