Maximum Average Subarray I(#643)

Category: Array, Sliding Window

๐Ÿงฉ Problem Statement

You are given an integer array `nums` containing `n` elements, and an integer `k`. Your task is to find a contiguous subarray of length exactly `k` that has the maximum average. Return this average value. Your answer is considered correct if it is within 10^-5 of the actual answer.

๐Ÿ“š Examples

Input: nums = [1, 12, -5, -6, 50, 3], k = 4

Output: 12.75000

Explanation: Subarray [12, -5, -6, 50] gives the maximum average 12.75.

Input: nums = [5], k = 1

Output: 5.00000

Explanation: Only one number, so average is the number itself.

๐Ÿง  Approach

Approach:

Sliding Window Technique

โ€ข First, compute the sum of the first `k` elements and store it as `subArray`.

โ€ข Calculate the average `subArray / k` and store it as initial `avg`.

โ€ข Slide the window by adding the next element and removing the one that just went out of the window.

โ€ข At each step, update the maximum average if the new one is higher.

โ€ข Finally, return the maximum average rounded to five decimal places using `.toFixed(5)`.

๐Ÿ’ป Code

// ๐Ÿ”น JavaScript Solution using Sliding Window
var findMaxAverage = function(nums, k) {
  let subArray = 0;
  for (let i = 0; i < k; i++) {
    subArray += nums[i];
  }
  let avg = subArray / k;

  for (let i = k; i < nums.length; i++) {
    subArray = subArray + nums[i] - nums[i - k];
    avg = Math.max(avg, subArray / k);
  }

  return avg.toFixed(5);
};

console.log(findMaxAverage([1, 12, -5, -6, 50, 3], 4)); // Output: 12.75000
console.log(findMaxAverage([5], 1)); // Output: 5.00000

๐Ÿ“ˆ Complexity

Time: O(n) โ€” We traverse the array once after the initial k-element sum.

Space: O(1) โ€” We use constant extra space.

๐ŸŽฌ Watch Explanation

๐Ÿ“Š Presentation (PPT)

๐Ÿ“ฅ Download PPT

๐Ÿ“Ž Resources