{"size": 836, "ext": "js", "max_stars_repo_path": "src/array/maximum-average-subarray-i.js", "max_stars_repo_name": "EslamHiko/javascript-problems-and-solutions", "max_stars_repo_stars_event_min_datetime": "2017-10-13T03:38:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:38:33.000Z", "max_issues_repo_path": "src/array/maximum-average-subarray-i.js", "max_issues_repo_name": "SimonXu100/javascript-problems-and-solutions", "max_issues_repo_issues_event_min_datetime": "2017-08-03T00:33:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-07T07:24:52.000Z", "max_forks_repo_path": "src/array/maximum-average-subarray-i.js", "max_forks_repo_name": "SimonXu100/javascript-problems-and-solutions", "max_forks_repo_forks_event_min_datetime": "2017-10-18T00:50:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T23:12:32.000Z"}
{"max_stars_count": 749, "max_issues_count": 215, "max_forks_count": 217, "avg_line_length": 19.9047619048, "max_line_length": 90, "alphanum_fraction": 0.5645933014}
/**
 * Maximum Average Subarray I
 *
 * 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
 * Output: 12.75
 *
 * Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
 *
 * Note:
 *
 * - 1 <= k <= n <= 30,000.
 * - Elements of the given array will be in the range [-10,000, 10,000].
 */

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
const findMaxAverage = (nums, k) => {
  let sum = 0;
  let max = -Infinity;

  for (let i = 0; i < nums.length; i++) {
    sum += nums[i];

    if (i >= k - 1) {
      max = Math.max(max, sum / k);
      sum -= nums[i - k + 1];
    }
  }

  return max;
};

export { findMaxAverage };
