forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum-average-subarray-ii.py
More file actions
29 lines (26 loc) · 910 Bytes
/
maximum-average-subarray-ii.py
File metadata and controls
29 lines (26 loc) · 910 Bytes
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
# Time: O(n)
# Space: O(n)
class Solution(object):
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
def getDelta(avg, nums, k):
accu = [0.0] * (len(nums) + 1)
minval_pos = None
delta = 0.0
for i in xrange(len(nums)):
accu[i+1] = nums[i] + accu[i] - avg
if i >= (k-1):
if minval_pos == None or accu[i-k+1] < accu[minval_pos]:
minval_pos = i-k+1
if accu[i+1] - accu[minval_pos] >= 0:
delta = max(delta, (accu[i+1] - accu[minval_pos]) / (i+1 - minval_pos))
return delta
left, delta = min(nums), float("inf")
while delta > 1e-5:
delta = getDelta(left, nums, k)
left += delta
return left