InterviewPrepKit

Home / Coding / Sliding Window

Maximum Average Subarray I

easy Original β†—
Solving tips
  • Recognize a fixed-size window: maximizing the average of length-k subarrays is the same as maximizing the sum, so divide by k once at the end.
  • Compute the first window's sum in O(k), then slide with an O(1) update: window_sum += nums[right] - nums[right-k].
  • Target O(n) time and O(1) space; a prefix-sum variant is O(n)/O(n) and useful when windows are not visited in sliding order.
  • Common pitfall: seed best with the first window sum or -inf (not 0), since all-negative inputs give a negative answer; the leaving index is exactly nums[right-k].

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 = 4 β†’ 12.75 β€” the window [12, -5, -6, 50] sums to 51, and 51 / 4 = 12.75.
  • nums = [5], k = 1 β†’ 5.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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.