Given an integer array nums
consisting of n
elements and an integer k
, return the maximum average value of a subarray of length k
. You need to compute the result as a floating-point number.
nums
and k
:
n
(the length of nums
) and k
?k <= n
?nums
array? (e.g., are they all positive, can they be negative?)We need an efficient way to find the maximum average subarray of length k
. A brute-force solution would involve checking all possible subarrays of length k
which would be very inefficient with time complexity of O(n*k). So, we will use a sliding window approach to achieve a time complexity of O(n).
k
elements.k
to get the maximum average.def findMaxAverage(nums, k):
# Compute the sum of the first window of size `k`
current_sum = sum(nums[:k])
max_sum = current_sum
# Slide the window from the start to the end of the array
for i in range(k, len(nums)):
# Update the sum for the new window
current_sum += nums[i] - nums[i - k]
# Update max_sum if we find a new maximum
if current_sum > max_sum:
max_sum = current_sum
# The maximum average is the maximum sum divided by `k`
return max_sum / k
# Example usage
nums = [1, 12, -5, -6, 50, 3]
k = 4
print(findMaxAverage(nums, k)) # Output should be 12.75
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?