[leetcode-644-Maximum Average Subarray II]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-644-Maximum Average Subarray II]相关的知识,希望对你有一定的参考价值。

Given an array consisting of n integers, find the contiguous subarray whose length is greater than or equal to 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:
when length is 5, maximum average value is 10.8,
when length is 6, maximum average value is 9.16667.
Thus return 12.75.

 

Note:

  1. 1 <= k <= n <= 10,000.
  2. Elements of the given array will be in range [-10,000, 10,000].
  3. The answer with the calculation error less than 10-5 will be accepted

思路:

用一个sum去记录从开始到当前元素之前的所有元素的和,即sum[i]记录下标从0到i-1的所有元素的和。

这样区间[i,j]的和就可以表示为sum[j+1] - sum[i].

还发现 两句话效率不一样,上一句会超时。。。

 ret = max(ret,(sum[i+window]-sum[i])/window);//超时。。。
                if (ret*window < (sum[i + window] - sum[i]))ret = (sum[i + window] - sum[i])/window;
double findMaxAverage1(vector<int>& nums, int k)
    {
        int n = nums.size();
        vector<double>sum(n + 1,0);
        for (int i = 0; i < n; i++)sum[i + 1] = sum[i] + nums[i];
        double ret = -1e4;
        for (int i = 0; i <= n - k;i++)
        {
            for (int window = k; window + i <= n;window++)
            {
                //ret = max(ret,(sum[i+window]-sum[i])/window);//超时。。。
                if (ret*window < (sum[i + window] - sum[i]))ret = (sum[i + window] - sum[i])/window;
            }
        }
        return ret;
    }

 

这种方法效率不是很高,看到有用二分查找思路的,还不是很懂,待优化。

以上是关于[leetcode-644-Maximum Average Subarray II]的主要内容,如果未能解决你的问题,请参考以下文章

如何从ave中的函数调用非x?

如何根据 PlaceID 列出 ave_rating,取其平均值并分配给所有具有 PlaceID 的 PlaceID。 [复制]

C博客作业--指针

[HAOI2008]糖果传递

买苹果

poj1004