iq.lab
Python starts when a code cell comes near or you run one
easySliding window target 15 min

Largest average window

You get a list of integers nums and a whole number k. A window is a block of k items that sit next to each other: positions i through i + k - 1. Of all the windows in nums, find the one whose items have the largest average, and return that average as a float.

A float can carry a tiny rounding error, so the tests pass any result within 0.00001 of the exact average.

Example 1
Inputnums = [4, 2, 8, 1, 6], k = 2Output5.0

The windows are [4, 2], [2, 8], [8, 1] and [1, 6]. [2, 8] has the largest sum, 10, so its average is 10 / 2 = 5.0.

Example 2
Inputnums = [-3, -1, -4, -2], k = 3Output-2.33333 (that is, -7 / 3)

The windows sum to -8 and -7. The larger is -7, and -7 / 3 is about -2.33333.

Example 3
Inputnums = [1, 2], k = 2Output1.5

The only window is the whole list. Its average is 1.5, a float, even though every item is an integer.

Constraints
  • 1 ≤ k ≤ len(nums) ≤ 105

  • -104 ≤ nums[i] ≤ 104

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.