643.Maximum Average Subarray I
643.Maximum Average Subarray I
难度:Easy 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.
1
Example 1:
2
3
Input: [1,12,-5,-6,50,3], k = 4
4
Output: 12.75
5
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
6
7
8
Note:
9
10
1 <= k <= n <= 30,000.
11
Elements of the given array will be in the range [-10,000, 10,000].
Copied!
窗口滑动,遍历一遍。
1
class Solution {
2
public:
3
double findMaxAverage(vector<int>& nums, int k) {
4
int sum=accumulate(nums.begin(),nums.begin()+k,0);
5
int maxSum=sum;
6
for(int i=k;i<nums.size();i++)
7
{
8
maxSum=max(maxSum, sum+=nums[i]-nums[i-k]);
9
}
10
return maxSum/double(k);
11
}
12
};
Copied!
执行用时 :164 ms, 在所有 C++ 提交中击败了94.19%的用户 内存消耗 :16.8 MB, 在所有 C++ 提交中击败了68.97%的用户
Copy link