643. Maximum Average Subarray I

问题:

求给定数组中,连续k个数的最大平均值。

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
 

Note:
1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].

  

解决方法:

依次求的每组连续k个数的平均值,同时依次比较取出两两之间的最大值

tip:问题点:简单每次重新计算连续k个数,则会超出要求时限

解决:滑动窗口法

sum[i] = sum[i-1] - nums[i-k] +nums[i]

nums=[1,2,3,4,5,6] k=4
sum[1,2,3,4]
    ^    ↓ 
sum[  2,3,4,5] = sum[1,2,3,4] - 1 + 5
^

代码参考:

 1 class Solution {
 2 public:
 3     double findMaxAverage(vector<int>& nums, int k) {
 4         double res = INT_MIN;
 5         double sum=0;
 6         for(int i=0; i<k; i++) sum+=nums[i];
 7         res = sum/k*1.0;
 8         for(int i=k; i<nums.size(); i++){
 9             sum=sum+nums[i]-nums[i-k];
10             double tmp = sum/k*1.0;
11             res = max(res, tmp);
12         }
13         return res;
14     }
15 };
posted @ 2020-03-15 12:18  habibah_chang  阅读(103)  评论(0编辑  收藏  举报