adding a sliding window problem

This commit is contained in:
Jidong Xiao
2023-11-05 00:03:38 -04:00
parent f80c0a5a4a
commit 1c30e6f4c8

View File

@@ -0,0 +1,28 @@
// sliding window problem.
// O(n) solution
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double result = INT_MIN;
double sum = 0.00;
int size = nums.size();
int low = 0;
int high = 0;
while(high<size){
sum += nums[high];
if(high-low+1 == k){
if(sum > result){
result = sum;
}
// always make sure there are no more than k elements in this sum.
sum -= nums[low];
// slide the window
low++;
}
// slide the window
high++;
}
result = result/k;
return result;
}
};