leetcode-643-Maximum Average Subarray I

题目描述:

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.

Example 1:

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. 1 <= k <= n <= 30,000.
  2. Elements of the given array will be in the range [-10,000, 10,000].

 

要完成的函数:

double findMaxAverage(vector<int>& nums, int k)

 

说明:

这道题目十分容易,给定一个vector和数值k,我们可以得到长度为k的多个连续的子vector,要求返回这些子vector中的最大平均值。

我们可以遍历一遍vector就得到了结果,存储和的最大值,最后除以k即可得到。

为了降低花费的时间,我们也不需要每次都计算k个元素的和,减去最前面一个和加上新增加的一个即可,类似于滑动窗口。

代码如下:

    double findMaxAverage(vector<int>& nums, int k) 
    {
        int s1=nums.size();
        int sum=0;
        for(int i=0;i<k;i++)
            sum+=nums[i];
        int i=1,max1=sum;
        while(i+k<=s1)
        {
            sum-=nums[i-1];
            sum+=nums[i+k-1];
            max1=max(max1,sum);
            i++;
        }
        return double(max1)/k;
    }

上述代码实测174ms,beats 81.87% of cpp submissions。

猜你喜欢

转载自www.cnblogs.com/king-3/p/9022543.html