class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
}
};
643. 子数组最大平均数 I
给你一个由 n
个元素组成的整数数组 nums
和一个整数 k
。
请你找出平均数最大且 长度为 k
的连续子数组,并输出该最大平均数。
任何误差小于 10-5
的答案都将被视为正确答案。
示例 1:
输入:nums = [1,12,-5,-6,50,3], k = 4 输出:12.75 解释:最大平均数 (12-5-6+50)/4 = 51/4 = 12.75
示例 2:
输入:nums = [5], k = 1 输出:5.00000
提示:
n == nums.length
1 <= k <= n <= 105
-104 <= nums[i] <= 104
相似题目
原站题解
python3 解法, 执行用时: 208 ms, 内存消耗: 25.5 MB, 提交时间: 2023-09-27 15:27:27
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: maxTotal = total = sum(nums[:k]) n = len(nums) for i in range(k, n): total = total - nums[i - k] + nums[i] maxTotal = max(maxTotal, total) return maxTotal / k
javascript 解法, 执行用时: 100 ms, 内存消耗: 52.5 MB, 提交时间: 2023-09-27 15:27:17
/** * @param {number[]} nums * @param {number} k * @return {number} */ var findMaxAverage = function(nums, k) { let sum = 0; const n = nums.length; for (let i = 0; i < k; i++) { sum += nums[i]; } let maxSum = sum; for (let i = k; i < n; i++) { sum = sum - nums[i - k] + nums[i]; maxSum = Math.max(maxSum, sum); } return maxSum / k; };
cpp 解法, 执行用时: 140 ms, 内存消耗: 107.3 MB, 提交时间: 2023-09-27 15:26:59
class Solution { public: double findMaxAverage(vector<int>& nums, int k) { int sum = 0; int n = nums.size(); for (int i = 0; i < k; i++) { sum += nums[i]; } int maxSum = sum; for (int i = k; i < n; i++) { sum = sum - nums[i - k] + nums[i]; maxSum = max(maxSum, sum); } return static_cast<double>(maxSum) / k; } };
java 解法, 执行用时: 2 ms, 内存消耗: 53 MB, 提交时间: 2023-09-27 15:26:43
class Solution { public double findMaxAverage(int[] nums, int k) { int sum = 0; int n = nums.length; for (int i = 0; i < k; i++) { sum += nums[i]; } int maxSum = sum; for (int i = k; i < n; i++) { sum = sum - nums[i - k] + nums[i]; maxSum = Math.max(maxSum, sum); } return 1.0 * maxSum / k; } }
golang 解法, 执行用时: 204 ms, 内存消耗: 8.8 MB, 提交时间: 2021-07-01 10:41:02
func findMaxAverage(nums []int, k int) float64 { ans, n := 0, len(nums) for i := 0; i < k; i++ { ans += nums[i] } s := ans for i := 1; i <= n-k; i++ { s += nums[i+k-1]-nums[i-1] ans = max(ans, s) } return float64(ans)/float64(k) } func max(x, y int) int { if x > y { return x } return y }