- Maximum Average Subarray
Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. You need to output the maximum average value.
Example
Example1
Input: nums = [1,12,-5,-6,50,3] and k = 4
Output: 12.75
Explanation:
Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Example2
Input: nums = [4,2,1,3,3] and k = 2
Output: 3.00
Explanation:
Maximum average is (3+3)/2 = 6/2 = 3.00
Notice
1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].
思路:滑动窗口。
记得maxResult初值设为numeric_limits::lowest();
要include。
代码如下:
#include <limits>
class Solution {
public:
/**
* @param nums: an array
* @param k: an integer
* @return: the maximum average value
*/
double findMaxAverage(vector<int> &nums, int k) {
int len = nums.size();
if (len == 0 || len < k) return 0.0;
double result = 0.0;
double maxResult = numeric_limits<double>::lowest();
double windowSum = 0;
for (int i = 0; i < len; ++i) {
windowSum += nums[i];
if (i >= k) windowSum -= nums[i - k];
maxResult = max(maxResult, windowSum);
}
return maxResult / k;
}
};