[LeetCode] 643. Maximum Average Subarray I

You are given an integer array nums consisting of n elements, and an integer k.

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.

Example 1:
Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75

Example 2:
Input: nums = [5], k = 1
Output: 5.00000

Constraints:
n == nums.length
1 <= k <= n <= 105
-104 <= nums[i] <= 104

子数组最大平均数 I。

给你一个由 n 个元素组成的整数数组 nums 和一个整数 k 。

请你找出平均数最大且 长度为 k 的连续子数组,并输出该最大平均数。

任何误差小于 10-5 的答案都将被视为正确答案。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-average-subarray-i
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

这道题的思路是滑动窗口,但是窗口的长度是固定的,为 k。我们先计算一下数组前 k 个数的和;然后从第 k + 1 个数开始,分别计算不同窗口里面数字的 sum,并且记录一个最大的 sum。最后再计算平均值。

复杂度

时间O(n)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 = k; i < nums.length; i++) {
sum = sum + nums[i] - nums[i - k];
max = Math.max(max, sum);
}
return max / k;
}
}

JavaScript实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findMaxAverage = function(nums, k) {
let sum = 0;
for (let i = 0; i < k; i++) {
sum += nums[i];
}
let maxSum = sum;
for (let i = k; i < nums.length; i++) {
sum = sum - nums[i - k] + nums[i];
maxSum = Math.max(maxSum, sum);
}
return 1.0 * maxSum / k;
};

[LeetCode] 643. Maximum Average Subarray I
https://shurui91.github.io/posts/2019896287.html
Author
Aaron Liu
Posted on
February 5, 2021
Licensed under