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
Input: nums = [5], k = 1
Output: 5.00000
๐ง 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.