643. Maximum Average Subarray I ¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14class Solution { public: double findMaxAverage(vector<int>& nums, int k) { double sum = accumulate(nums.begin(), nums.begin() + 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; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class 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; } } 1 2 3 4 5 6 7 8 9 10class 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