Question:
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:
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
Solution:
/*
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findMaxAverage = function(nums, k) {
// 和最大即平均值最大,转换为求和问题
let sum = 0;
for(let j=0; j<k; j++){
sum += nums[j]
}
let max= sum ;
for(let i=k; i<nums.length; i++){
sum = sum - nums[i-k] + nums[i];
max = Math.max(max,sum);
}
return max/k
};
Runtime: 96 ms, faster than 98.08% of JavaScript online submissions for Maximum Average Subarray I.