首页 > 代码库 > [leetcode-644-Maximum Average Subarray II]
[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 <=
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; }
这种方法效率不是很高,看到有用二分查找思路的,还不是很懂,待优化。
[leetcode-644-Maximum Average Subarray II]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。