LeetCode Solutions
643. Maximum Average Subarray I
Time: $O(n)$ Space: $O(1)$
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double sum = accumulate(begin(nums), begin(nums) + k, 0);
double ans = sum;
for (int i = k; i < nums.size(); ++i) {
sum += nums[i] - nums[i - k];
ans = max(ans, sum);
}
return ans / k;
}
};
class Solution {
public double findMaxAverage(int[] nums, int k) {
double sum = 0;
for (int i = 0; i < k; ++i)
sum += nums[i];
double ans = sum;
for (int i = k; i < nums.length; ++i) {
sum += nums[i] - nums[i - k];
ans = Math.max(ans, sum);
}
return ans / k;
}
}
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
summ = sum(nums[:k])
ans = summ
for i in range(k, len(nums)):
summ += nums[i] - nums[i - k]
ans = max(ans, summ)
return ans / k