The 30 second answer
I keep a running sum of a window of length k. I start with the first k elements, then slide one step at a time by adding the new right value and subtracting the value that left on the left. I track the maximum sum and divide by k at the end. Linear time, constant extra space.
Problem Given an integer array and a window length k, return the maximum average of any contiguous subarray of length k. The answer is a floating-point value. Original: LeetCode 643: Maximum Average Subarray I.
Understanding the prompt Every candidate has the same length k, so maximising the average is the same as maximising the sum. You do not need to return the subarray itself, only the average.
Pattern recognition A fixed-size sliding window: each step adds one element on the right and drops one on the left.
Brute force Compute the sum of nums[i..i+k) for every i: O(n ยท k).
Optimal Sum the first k elements, then for each later index add nums[i] and subtract nums[i โ k], keeping the best sum. The average is that sum divided by k as a double. Integer division would truncate, so you must convert to double.
Alternatives Prefix sums give the same O(n) time with O(n) extra space, which is unnecessary when the window length is fixed.
Java solution
public class MaximumAverageSubarrayI {
static double findMaxAverage(int[] nums, int k) {
int sum = 0;
for (int i = 0; i < k; i++) sum += nums[i];
int best = sum;
for (int i = k; i < nums.length; i++) {
sum += nums[i] - nums[i - k];
best = Math.max(best, sum);
}
return best / (double) k;
}
public static void main(String[] args) {
System.out.println(findMaxAverage(new int[] {1, 12, -5, -6, 50, 3}, 4)); // 12.75
System.out.println(findMaxAverage(new int[] {5}, 1)); // 5.0
}
}Complexity O(n) time, O(1) extra space.
Edge cases
- k equals the length of the array: the answer is the average of the whole array.
- A single element, as in [5] with k = 1, returns 5.0.
- Negative values, which can make the first window worse than a later one.
Follow-ups
- Maximum sum of a window of length k is the same code without the final division.
- A variable-length window with a sum constraint is Minimum Size Subarray Sum.
Tests [1,12,-5,-6,50,3] with k=4 returns 12.75, the average of [12,-5,-6,50]. [5] with k=1 returns 5.0.
How to say it in the interview "I keep a running sum of k elements. Each step I add the new right value and subtract the value that just left, and I remember the best sum. The maximum average is that sum divided by k. Linear time, constant space."
Sources (1)
- LeetCode 643: Maximum Average Subarray Ileetcode.com