154. Best Average Window

A weather station records the temperature at noon each day, and the readings are stored in the array nums. A meteorologist wants to find the warmest stretch of exactly k consecutive days, measured by the average temperature over those days.

Return the largest average value among all windows of exactly k consecutive elements of nums. Readings can be negative. Any answer within 10^-6 of the true value is accepted, so floating-point output is fine. It is guaranteed that k does not exceed the length of the array.

Example 1

Input:
nums = [4,-2,9,1,6,-3], k = 3
Output:
5.333333333333333
Explanation:

The window sums are 11, 8, 16 and 4. The best is 16 from [9,1,6], and 16 / 3 = 5.33333.

Example 2

Input:
nums = [7], k = 1
Output:
7
Explanation:

There is a single window [7], so the answer is 7.0.

Constraints

1 ≤ k ≤ nums.length ≤ 105

-104 ≤ nums[i] ≤ 104

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
Tolerance
0.000001

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…