Maximum Average Subarray I
Find the largest average of k numbers that sit next to each other, with one running sum.
Given an array of integers numskkkk
Example 1
Output: 12.75
Explanation: (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75.
Example 2
Output: 5.0
The Idea
Think of the numbers in Example 1 as a shop's profit on six days in a row: 1, 12, -5, -6, 50 and 3, where a negative number is a day with a loss. Which four days in a row did best on average?
Six days hold three runs of four: days 1 to 4, days 2 to 5 and days 3 to 6. Their sums are 2, 51 and 42, so their averages are 0.5, 12.75 and 10.5. The best is 12.75, which matches the expected output.
Notice that every run has the same length, four. Dividing each sum by the same 4 keeps their order, so the run with the largest sum also has the largest average. That leaves one question: do we have to add up every run from scratch?
Picture a frame that covers four numbers at a time and moves one step right each time. That frame is called a window. Look at the picture below.
In the row labelled window 1, the frame covers 1, 12, -5 and -6, and their sum is 2. In window 2 it has moved one step right. The 1 marked dropped has left, the 50 marked added has come in, and the middle three numbers are the same. So the new sum is 2 + 50 - 1 = 51, with no need to add 12, -5 and -6 again. Window 3 works the same way: 51 + 3 - 12 = 42.
On the right, best keeps the largest sum seen so far. It becomes 51 at window 2 and stays there. So each move costs one addition and one subtraction, however long the window is. Moving a fixed-size frame along an array like this is called the sliding window technique.
Solution Approach
Turning that idea into code means settling four things: how to update the sum, where the best sum starts, how to keep the sum from overflowing, and how to turn the best sum into an average.
Updating the sum as the window slides
Why not add up each window from scratch? That costs kk
If the window ends at position inums[i]knums[i - k]k
Where the best sum starts
What should best
Keeping the sum from overflowing
Can the sum grow too large? Fifty thousand numbers of 100,000 each already add up to 5 billion, more than the 2,147,483,647 that a Java intsumbestlongnums[i] - nums[i - k]nums[i]long
Turning the best sum into an average
Since the largest sum belongs to the largest average, the division happens once, at the end. In Java, dividing a whole number by a whole number drops the fraction: 51 / 4 gives 12, not 12.75. Casting bestdouble
Java Solution
The method findMaxAverage
- First, add up the first
numbers intok with a loop. That is window 1.sum - Start
at that sum.best - A second loop moves
fromi to the end of the array, sok is always the last position of the current window. Each step addsi , subtractsnums[i] , and keeps the larger ofnums[i - k] andbest insum .best - Return
, the largest average.(double) best / k
The mainint
public class MaximumAverageSubarrayI {
public static double findMaxAverage(int[] nums, int k) {
long sum = 0;
for (int i = 0; i < k; i++) {
sum += nums[i]; // the first window
}
long best = sum;
for (int i = k; i < nums.length; i++) {
sum += (long) nums[i] - nums[i - k]; // one number in, one number out
best = Math.max(best, sum);
}
return (double) best / k;
}
public static void main(String[] args) {
System.out.println(findMaxAverage(new int[] {1, 12, -5, -6, 50, 3}, 4));
System.out.println(findMaxAverage(new int[] {5}, 1));
System.out.println(findMaxAverage(new int[] {-1, -3}, 1));
System.out.println(findMaxAverage(new int[] {9, 7, 1, 2, 3}, 2));
System.out.println(findMaxAverage(new int[] {4, -1, 2}, 3));
System.out.println(findMaxAverage(new int[] {-2000000000, 2000000000}, 1));
}
}
Running it prints:
12.75
5.0
-1.0
8.0
1.6666666666666667
2.0E9
The 12.75 and 5.0 at the top match the two examples. Look at the third line, -1.0. It comes from [-1, -3]kbest
The 8.0 comes from [9, 7, 1, 2, 3]kbest[4, -1, 2]
The last line, 2.0E9, is Java's way of writing 2.0 × 109, two billion. The second window holds 2,000,000,000, and sliding to it subtracts the -2,000,000,000 that leaves. The true difference, 4 billion, does not fit in an int(long)
Complexity
The work is one pass over the array, split into the first window and the slides after it.
- Time: O(n), because the first loop reads the first
numbers and the second loop reads each of the other numbers once, with one addition, one subtraction and one comparison each. Adding every window from scratch would take O(n × k).k - Space: O(1), because the method keeps only
,sum and the loop index, whatever the size of the array.best
The same running sum, with a count instead of a maximum, solves