leetcode/0643_maximum-average-subarray-i/python3/solution.py

26 lines
899 B
Python
Raw Normal View History

2022-04-14 23:54:03 +00:00
# Time: O(N)
# Space: O(1)
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
# Sliding window approach
max_average = float("-inf")
moving_sum = 0.0
window_start = 0
for i in range(0, len(nums)):
moving_sum += nums[i]
# Need to start computing averages only at this point.
# e.g. Suppose nums = [0, 1, 2, 3] and k = 3
if i >= k - 1:
# e.g. When i = 3 - 1 = 2, start checking for max average
max_average = max(moving_sum / k, max_average)
# e.g. Remove element at beginning of window, i.e 0 from [0...2]
moving_sum -= nums[window_start]
# e.g. Move window position from 0 to 1
window_start += 1
return max_average