Maximum Average of K Consecutive
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
Algorithm Flow
Solution Approach
Use a sliding window to maintain the sum incrementally and compute averages.
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
class Solution {
public int solution(int[] nums, int k) {
return 0;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
