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:

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

Solution:

  1. /*
  2. * @param {number[]} nums
  3. * @param {number} k
  4. * @return {number}
  5. */
  6. var findMaxAverage = function(nums, k) {
  7. // 和最大即平均值最大,转换为求和问题
  8. let sum = 0;
  9. for(let j=0; j<k; j++){
  10. sum += nums[j]
  11. }
  12. let max= sum ;
  13. for(let i=k; i<nums.length; i++){
  14. sum = sum - nums[i-k] + nums[i];
  15. max = Math.max(max,sum);
  16. }
  17. return max/k
  18. };

Runtime: 96 ms, faster than 98.08% of JavaScript online submissions for Maximum Average Subarray I.