643. Maximum Average Subarray I*
https://leetcode.com/problems/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].
解题思路
这题比较简单, 每次移动长度为 k 的方框, 求方框元素的和, 当向右移动方框时, 将新元素加入方框, 并将方框中的第一个元素给去除, 更新连续子数组和的最大值.
C++ 实现 1
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int res = std::accumulate(nums.begin(), nums.begin() + k, 0);
int imax = res;
for (int i = k; i < nums.size(); ++i) {
res += nums[i] - nums[i - k];
imax = max(imax, res);
}
return imax / double(k);
}
};
本文详细解析了LeetCode上的643题:最大平均子数组I,介绍了如何通过滑动窗口的方法高效求解给定长度k的连续子数组的最大平均值。适用于希望提高算法理解和编程技巧的读者。

480

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



