643. Maximum Average Subarray I

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double ret = -10000;
int n = nums.size();
int l= 0, r = 0;
double window = 0;
while(r<n)
{
window += nums[r++];
if(r-l == k)
{
ret =max(ret, window/k);
window-=nums[l++];
}
}
return ret;
}
};

analysis

  • time complexity O(n)
  • space complexity O(1)