Description: You are given an integer array nums consisting of n elements, and an integer k. Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10^-5 will be accepted.
Code:
def findMaxAverage(self, nums: List[int], k: int) -> float:
curr_sum = 0
for i in range(k):
curr_sum += nums[i]
max_sum = curr_sum
for i in range(k, len(nums)):
curr_sum += nums[i] - nums[i - k]
max_sum = max(max_sum, curr_sum)
return max_sum / k
Efficiency:
Time Complexity: O(n), 1 <= k <= n
Space Complexity: O(1)
Test:
# Tolerance note: allow small floating-point precision error with abs(actual - expected) < 1e-5
# Test: Mixed positive and negative values
# Max average = (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
assert abs(findMaxAverage([1, 12, -5, -6, 50, 3], 4) - 12.75) < 1e-5
# Test: Smallest valid input (k = 1)
# Max average = 5 / 1 = 5.0
assert abs(findMaxAverage([5], 1) - 5.0) < 1e-5