643. Maximum Average Subarray I
You are given an integer array
numsconsisting ofnelements, and an integerk.Find a contiguous subarray whose length is equal to
kthat has the maximum average value and return this value. Any answer with a calculation error less than10-5will be accepted.Example 1:
Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75Example 2:
Input: nums = [5], k = 1
Output: 5.00000
def findMaxAverage(self, nums: List[int], k: int) -> float:
curr_sum=max_sum=sum(nums[:k])
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