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 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].
思路
1、一开始,想找下看有没有规律,但是数据是混乱的并且对位置有要求,排除了排序、哈希等的方法;
2、然后,先想下爆破,每次计算指定k个数据的和,找出最大的,这样就可,一开始先用这种方式解决,提交后的延时大概1.5s左右
3、进行优化,上面这种方式复杂度为o(n*k),但是在计算和的操作上是可以避免了,因为中间的数据可以不变,只要变动边上的数据就可以,类似于滑动窗口,因此采用滑动窗口的方式
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int max_value = 0;
int i = 0;
for (; i<k; i++)
{
max_value += nums[i];
}
int temp=max_value;
if (k < nums.size())
{
for (; i < nums.size(); i++)
{
temp = temp + nums[i] - nums[i - k];
max_value = max(temp,max_value);
}
}
return (double)max_value / k;
}
};
本文介绍了一种高效算法,用于从整数数组中找到长度为k的连续子数组,该子数组具有最大平均值,并输出这个最大平均值。通过滑动窗口技术优化计算过程,显著提升了算法效率。
414

被折叠的 条评论
为什么被折叠?



