Leetcode # 643. Maximum Average Subarray I
- 2023.08.28
- ★ Easy LeetCode Sliding Window
Problem
https://leetcode.com/problems/maximum-average-subarray-i
Solution
Time Complexity: O(len(nums))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
ans = -inf
left = curr = 0
for right in range(len(nums)):
# do logic here to add arr[right] to curr
curr += nums[right]
while right - left + 1 > k:
# remove arr[left] from curr
curr -= nums[left]
left += 1
# update ans
if right - left + 1 == k:
ans = max(ans, curr)
return ans / k
Last Updated on 2023/08/28 by A1go