Maximum Average Subarray of Length k

Given an array of n integers, find the contiguous subarray of given length k that has the maximum average value. Output the maximum average value.

Problem

Given an array 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
Example output: 12.75

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The solution is to iterate through the array and keep track of the sum of the first k elements.
// Then, for each subsequent element, subtract the first element of the previous subarray and add the current element.
// This way, we only have to iterate through the array once, and we don't have to create any new arrays.
// The time complexity is O(n) and the space complexity is O(1).

function findMaxAverage(nums, k) {
  let sum = 0;
  for (let i = 0; i < k; i++) {
    sum += nums[i];
  }
  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;
}

A.I. Evaluation of the Solution

The candidate's solution is correct and solves the problem. The approach is good, iterating through the array once and keeping track of the sum of the previous k elements. The time complexity is O(n) and the space complexity is O(1).

Evaluated at: 2022-12-03 02:15:36