题目: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 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].
个人代码
public double findMaxAverage(int[] nums, int k) {
int length = nums.length;
double sum;
double average;
double maxAverage = -10000;
for(int i = 0; i <=length-k; i++) {
sum = 0;
for (int j = i; j < i+k; j++) {
sum = sum+nums[j];
}
average = sum/k;
if(average > maxAverage)
maxAverage = average;
}
return maxAverage;
}
官方答案
不是先创建一个累积和数组,然后遍历它来确定所需的和,
我们只需遍历一次num,然后继续确定k长度子数组的可能和。
为了理解这个想法,假设我们已经知道了从索引i到索引i+k的元素之和,假设它是x。
现在,要确定从索引i+1到索引i+k+1的元素之和,我们需要做的就是从x减去元素nums[i],然后将元素nums[i+k+1]添加到x。
我们可以根据这个想法来执行我们的过程,并确定可能的最大平均值。
Complexity Analysis
Time complexity : O(n)O(n). We iterate over the given numsnums array of length nn once only.
Space complexity : O(1)O(1). Constant extra space is used.
public double findMaxAverage(int[] nums, int k) {
double sum=0;
for(int i=0;i<k;i++)
sum+=nums[i];
double res=sum;
for(int i=k;i<nums.length;i++){
sum+=nums[i]-nums[i-k];
res=Math.max(res,sum);
}
return res/k;
}
个人理解
以下面这个为例
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
先将前4个捆绑起来,看成一个整体sum,然后依次右移,将右边的数字加进sum来,左边的数字减sum出去,保证连续4个数字
本题的关键
在于求连续的子字数组,才能使用捆绑