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 nums and a number k, look at every run of k numbers that sit next to each other in the array, and return the largest average among those runs. Such a run is called a subarray of length k. The array has at least k numbers.

Example 1
Input: nums = [1, 12, -5, -6, 50, 3], k = 4
Output: 12.75
Explanation: (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75.
Example 2
Input: nums = [5], k = 1
Output: 5.0
Solution

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.

The array 1, 12, -5, -6, 50, 3 with a window of four numbers in three positions. Window 1 sums to 2. Window 2 adds 50 and drops 1, giving 51, the best. Window 3 adds 3 and drops 12, giving 42.

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 k additions per window. With 100,000 numbers and k = 50,000, there are 50,001 windows, which is about 2.5 billion additions. Sliding instead adds the number that enters and subtracts the number that leaves, two steps per window.

If the window ends at position i, the number entering is nums[i]. The number leaving is the one k places further left, nums[i - k]. In the picture, window 2 ends at index 4, and with k = 4 the dropped number sits at index 0.

Where the best sum starts

What should best hold before any comparison? The sum of window 1. Starting at 0 looks harmless, but when every window has a negative sum, no window ever beats 0, and the answer would be an average that no window has.

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 int can hold. Going past that limit wraps round to the most negative values, which is called overflow. So sum and best are long values, which hold far bigger numbers. The difference nums[i] - nums[i - k] can overflow too, so the code casts nums[i] to long before subtracting.

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 best to double first keeps the fraction.

Java Solution

The method findMaxAverage works in these steps:

  1. First, add up the first k numbers into sum with a loop. That is window 1.
  2. Start best at that sum.
  3. A second loop moves i from k to the end of the array, so i is always the last position of the current window. Each step adds nums[i], subtracts nums[i - k], and keeps the larger of best and sum in best.
  4. Return (double) best / k, the largest average.

The main method runs both examples, an array of only negative numbers, an array whose best window is the first one, a window as long as the whole array, and two numbers whose difference overflows an int.

Java
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:

Output
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] with k = 1, where both windows are negative. A version that starts best at 0 prints 0.0 for this input, an average that no window has.

The 8.0 comes from [9, 7, 1, 2, 3] with k = 2. The window sums are 16, 8, 3 and 5, so the winner is window 1, the one best starts from. In [4, -1, 2] the window covers all three numbers, so the second loop never runs, and the answer is 5 / 3, printed as 1.6666666666666667.

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. Without the (long) cast it overflows, and that version prints -2.0E9 instead.

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 k 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).
  • Space: O(1), because the method keeps only sum, best and the loop index, whatever the size of the array.

The same running sum, with a count instead of a maximum, solves Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold.