Maximum Average Subarray I

(#643), Easy

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

Sliding Window Technique

  • Calculate the sum of the first `k` elements and store it in `subArray`.
  • Initialize the maximum average `avg` as `subArray / k`.
  • Iterate from index `k` to the end of the array:
  • - At each step, update the sum by adding the new element and subtracting the element that is sliding out of the window: `subArray = subArray + nums[i] - nums[i - k]`.
  • - Recalculate the average and update `avg` if it's higher.
  • Return the final maximum average rounded to 5 decimal places.
// 🔹 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)

Space: O(1)

Watch Explanation

📊 Presentation (PPT)

📥 Download PPT

📎 Resources