644. Maximum Average Subarray II(题目链接)
Hard
Given an array consisting of n
integers, find the contiguous subarray whose length is greater than or equal to k
that has the maximum average value. And you need to output the maximum average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation:
when length is 5, maximum average value is 10.8,
when length is 6, maximum average value is 9.16667.
Thus return 12.75.
Note:
- 1 <=
k
<=n
<= 10,000. - Elements of the given array will be in range [-10,000, 10,000].
- The answer with the calculation error less than 10-5 will be accepted.
思路:二分法,二分平均值
参考:https://www.cnblogs.com/grandyang/p/8021421.html
https://blog.csdn.net/zjucor/article/details/75199933
平均值一定在nums的最大值与最小值之间,我们每次二分取得平均值。
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
min_ave, max_ave= min(nums), max(nums)
def check(m):
diff = [0] * len(nums)
for i in range(len(nums)):
diff[i] = nums[i] - m
sum1 = 0
for i in range(k):
sum1 += diff[i]
if sum1 >= 0:
return True
min_left, sum2 = 0, 0
for i in range(k, len(nums)):
sum2 += diff[i - k]
sum1 += diff[i]
min_left = min(min_left, sum2)
if sum1 - min_left >= 0:
return True
return False
low, high = min_ave, max_ave
while high - low >= pow(10, -5):
mid = (low + high) / 2
if check(mid):
low = mid
else:
high = mid
return low
拓展:如果让求最小的平均值