Skip to content
Problem 643 · LeetCode 643(opens in a new tab)

Maximum Average Subarray I

EasyArrays

You are given a list of whole numbers, nums, and a length k. Look at every run of k neighbouring numbers in the list (a window that does not skip anything).

Return the highest average that any such window has. Answers within 0.00001 of the true value are accepted.

Example 1

Input:  nums = [2, 9, -3, 4, 8, -1], k = 4
Output: 4.5
Why:    9 - 3 + 4 + 8 = 18, and 18 / 4 = 4.5
2 more examples and the constraints

Example 2

Input:  nums = [-7], k = 1
Output: -7.0
Why:    the only window is the single number

Example 3

Input:  nums = [-3, -1, -2], k = 2
Output: -1.5
Why:    (-1 + -2) / 2 beats (-3 + -1) / 2

Constraints

  • 1 ≤ k ≤ length of nums ≤ 100,000
  • −10,000 ≤ each number ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Add up every windowO(n·k)
  2. Sliding windowO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbers, k = 50,000Verdict
Add up every windowO(n·k)
Too slow when k is large
Sliding windowO(n)
Best; one pass

n = how many numbers are in the list, k = the window length.

Edge cases to test

  • Window is the whole list. With k = n there is exactly one window; the loop that slides never runs.
  • Window of one. With k = 1 the answer is simply the largest number.
  • All negative. Start best at the first window, not at 0, or [-3, -1, -2] would wrongly give 0.
  • Answer is not a whole number. Divide as a decimal: in Java and C++, 18 / 4 in integers would give 4, not 4.5.

Common mistakes

  • Starting the best sum at 0, which is wrong when every window adds up to less than 0.
  • Dividing two integers, so the fraction is cut off before it is returned.
  • Sliding off by one: taking away nums[i − k + 1] instead of nums[i − k].

How to talk through it

  1. 1Clarify. The window must be exactly k long and made of neighbours? Can numbers be negative?
  2. 2Give the brute force. Add up every window from scratch: O(n·k), too slow when k is near n.
  3. 3Spot the overlap. Next to each other, two windows differ by one number in and one number out.
  4. 4Code the slide. Sum the first window, then add the new number and take away the old one; compare sums and divide once.
  5. 5Test out loud. Run k = n, k = 1 and an all-negative list before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?