643. Maximum Average Subarray I(Leetcode每日一題-2021.02.04)
阿新 • • 發佈:2021-02-05
技術標籤:leetcode每日一題202102leetcode雙指標leetcode陣列
Problem
Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.
Note:
- 1 <= k <= n <= 30,000.
- Elements of the given array will be in the range [-10,000, 10,000].
Example
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Solution
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double res = -INT_MAX;
double sum = 0;
for(int i = 0,j=0;i< nums.size();)
{
sum += nums[i];
if(i-j+1 < k)
{
++i;
}
else
{
res = max(res,sum/k);
++i;
sum -= nums[j];
++j;
}
}
return res;
}
};