![[Leetcode]643. Maximum Average Subarray I [Leetcode]643. Maximum Average Subarray I](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
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].
思路:把数组里每 K 个连续
class Solution {
public double findMaxAverage(int[] nums, int k) {
double sum = 0;
for (int i = 0; i < k; i++)
sum += nums[i];
double max = sum;
for (int i = 0; i < nums.length - k; i++){
sum += nums[i+k] - nums[i];
max = Math.max(max, sum);
}
return max / k;
}
}
元素看作一个整体,然后一步一步地移动,比较这 K 个元素合与当前最大合 max 的大小。