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.
For example:
nums = [1, 12, -5, -6, 50, 3], k = 4
The maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
So the correct output is 12.75000
As another example:
nums = [5], k = 1
In this case, the correct output is 5.00000
How would you solve this problem efficiently?
A brute-force approach would involve iterating through all possible subarrays of length k
, calculating the average of each subarray, and keeping track of the maximum average encountered. This involves nested loops, making it less efficient.
def find_max_average_naive(nums, k):
n = len(nums)
max_avg = float('-inf')
for i in range(n - k + 1):
current_sum = 0
for j in range(i, i + k):
current_sum += nums[j]
current_avg = current_sum / k
max_avg = max(max_avg, current_avg)
return max_avg
Big O Analysis:
nums
. This is due to the nested loops.A more efficient approach is to use the sliding window technique. We first calculate the sum of the first k
elements. Then, we slide the window by one element at a time, subtracting the element that leaves the window and adding the element that enters the window. This allows us to update the sum in O(1) time, significantly reducing the overall time complexity.
def find_max_average(nums, k):
n = len(nums)
current_sum = sum(nums[:k])
max_sum = current_sum
for i in range(k, n):
current_sum += nums[i] - nums[i - k]
max_sum = max(max_sum, current_sum)
return max_sum / k
Big O Analysis:
nums
. This is because we iterate through the array only once.1 <= k <= n
, so this case is not applicable.k
is 1, the maximum average is simply the maximum element in the array.-10^4
and 10^4
. We need to consider the possibility of integer overflow if k
is large and the numbers are also large. Using float
can mitigate this risk, as shown in the examples above.