Javascript sliding window, time O(n), space O(1) and one pass solution


  • 0
    /**
     * @param {number[]} nums
     * @param {number} k
     * @return {number}
     */
    var findMaxAverage = function(nums, k) {
        let total = 0;
        let maxAvg = Number.MIN_SAFE_INTEGER;
        for (let i = 0; i < nums.length; i++) {
          total += nums[i];
          if (i < k-1) {
            continue;
          }
          maxAvg = Math.max(maxAvg, (total/k));
          total -= nums[(i+1) - k];
        }
        return maxAvg;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.