InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Sliding Window

Maximum Average Subarray I

easy Original ↗ 00:00

Problem

You are given an integer array nums and an integer k. Among all contiguous subarrays of exactly length k, find the one with the largest average value and return that average as a float.

Answers within 10^-5 of the true value are accepted, so ordinary floating-point division is fine.

Examples

  • nums = [1, 12, -5, -6, 50, 3], k = 412.75 — the window [12, -5, -6, 50] sums to 51, and 51 / 4 = 12.75.
  • nums = [5], k = 15.0 — the only window is the single element.
  • nums = [-1, -2, -3], k = 2-1.5 — with all-negative input the best window is [-1, -2]; the answer can be negative.

Constraints

  • 1 <= k <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4

Recomputing each window’s sum from scratch costs O(n·k) — about 10^10 operations in the worst case. The expected solution reuses work between adjacent windows and runs in O(n).

Think about it first

Hint 1 Maximizing the average of a fixed-length window is the same as maximizing its sum — divide by k once at the very end.
Hint 2 Two windows of length k starting at i and i + 1 overlap in all but two elements. How do their sums differ?
Hint 3 Compute the sum of the first k elements once. Then slide: for each new position, add the element entering on the right and subtract the element leaving on the left — an O(1) update. Track the maximum sum seen.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug