438/670

438. Maximum Average Subarray I

Easy

You are given an integer array nums and an integer k. Among all contiguous subarrays of nums whose length is exactly k, find the one with the largest average value.

Your function receives nums and k and returns that maximum average as a floating-point number. The program prints it rounded to exactly 5 digits after the decimal point (for example 12.75000), so any answer within normal floating-point precision is safe.

Example 1:

Input: nums = [1, 12, -5, -6, 50, 3], k = 4

Output: 12.75

Explanation: The length-4 windows have sums 2, 51, and 42. The best is [12, -5, -6, 50] with sum 51, so the answer is 51 / 4 = 12.75.

Example 2:

Input: nums = [5], k = 1

Output: 5.0

Explanation: There is only one window of length 1, so its average 5.0 is the answer.

Constraints:

  • 1 ≤ k ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴

Hints:

All windows have the same length k, so their averages compare exactly like their sums. Maximize the window sum and divide by k once at the very end.

When the window slides one position to the right, only two elements change: nums[i] enters and nums[i - k] leaves. Update the running sum in O(1) instead of re-adding k numbers.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [1, 12, -5, -6, 50, 3], k = 4

Expected output: 12.75