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 <=
k
<=n
<= 10,000. - Elements of the given array will be in range [-10,000, 10,000].
- 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; }
这种方法效率不是很高,看到有用二分查找思路的,还不是很懂,待优化。