[LeetCode] Maximum Average Subarray I

643. Maximum Average Subarray I

You are given an integer array nums consisting of n elements, and an integer k.

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double res = -1e5 - 1;
int sum = 0;
for(int i = 0; i < nums.size(); i++) {
sum += nums[i];
if(i >= k) sum -= nums[i-k];
if(i + 1 >= k) res = max(res, 1. * sum / k);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/30/PS/LeetCode/maximum-average-subarray-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.