Given n integers, find out the continuous sub array with the largest average and length k, and output the maximum average

Time:2022-5-7

Given n integers, find out the continuous sub array with the largest average and length k, and output the maximum average.

Example:

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

Tips:

1 <= k <= n <= 30,000。
Given data range [- 10000, 10000].

Source: leetcode
Link: https://leetcode-cn.com/probl…

Detailed introduction to sliding window solution:
https://leetcode-cn.com/probl…

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var findMaxAverage = function(nums, k) {
    let sum = 0 ,length = nums.length;
    for(let i = 0; i <k ;i ++){
        sum += nums[i]
    }

    var maxSum = sum;
    for(let i = k ; i < length; i ++){
        sum = sum - nums[i-k] +nums[i]
        maxSum = Math.max(maxSum,sum)
    }
    return maxSum/k

};