Ctrl K

Best Window Average

Easy
A sensor logged a series of integer readings, readings. Pick width consecutive readings whose arithmetic mean is as large as possible and return that mean. An answer within 10⁻⁵ of the exact value is accepted. Recomputing each window's sum from scratch costs O(n · width); aim for O(n).
Example 1
readings=[3, -2, 7, 8, -1, 4], width=3 → 4.666666666666667

Windows of length 3: [3, -2, 7] → 8, [-2, 7, 8] → 13, [7, 8, -1] → 14, [8, -1, 4] → 11. The best sum is 14, so the average is 14 / 3 ≈ 4.66667.

Example 2
readings=[-6, -4, -9], width=2 → -5.0

All values are negative; the best window is [-6, -4] with average -5.0.

Example 3
readings=[10], width=1 → 10.0
Constraints
  • 1 ≤ width ≤ len(readings) ≤ 10⁵
  • -10⁴ ≤ readings[i] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRepeat Within Reach EasyValues One Apart EasyStep Streak Score EasyNeighbour Sums Around a Circle EasyTightest Group of Scores Easy
loading Python…
Input
readings=[3, -2, 7, 8, -1, 4], width=3
Expected
4.666666666666667

Run checks the first 3 tests in your browser. Submit checks all 97 tests on the server, hidden ones included.