[Leetcode]643. Maximum Average Subarray I

时间:2023-03-10 04:22:49
[Leetcode]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. 1 <= k <= n <= 30,000.
  2. 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 的大小。