-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path617.maximum-average-subarray-ii.py
71 lines (61 loc) · 1.54 KB
/
617.maximum-average-subarray-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Tag: Binary Search on Answer, Binary Search
# Time: O(Nlog(A/ε))
# Space: O(N)
# Ref: Leetcode-644
# Note: -
# Given an array with positive and negative numbers, find the `maximum average subarray` which length should be greater or equal to given length `k`.
#
# ---
#
# Example 1:
# ```
# Input:
# [1,12,-5,-6,50,3]
# 3
# Output:
# 15.667
# Explanation:
# (-6 + 50 + 3) / 3 = 15.667
# ```
#
# Example 2:
# ```
# Input:
# [5]
# 1
# Output:
# 5.000
# ```
#
# It's guaranteed that the size of the array is greater or equal to *k*.
# Only unsigned `0` results are allowed to pass when `0` is the return value
from typing import (
List,
)
class Solution:
"""
@param nums: an array with positive and negative numbers
@param k: an integer
@return: the maximum average
"""
def max_average(self, nums: List[int], k: int) -> float:
# write your code here
left = min(nums)
right = max(nums)
while right - left > 1e-5:
mid = (left +right) / 2.0
if self.fit(nums, k, mid):
left = mid
else:
right = mid
return left
def fit(self, nums: list, k: int, average:int) -> bool:
prefix = [0]
for i in range(len(nums)):
prefix.append(prefix[-1] + nums[i] - average)
min_prefix = 0
for i in range(k, len(prefix)):
if prefix[i] - min_prefix >= 0:
return True;
min_prefix = min(min_prefix, prefix[i - k + 1])
return False