643. Maximum Average Subarray I
Description
You are given an integer array nums
consisting of n
elements, and an integer k
.
Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10^-5
will be accepted.
Example 1:
Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
Example 2:
Input: nums = [5], k = 1
Output: 5.00000
Constraints:
n == nums.length
1 <= k <= n <= 10^5
-10^4 <= nums[i] <= 10^4
My Solution
// failed: Time Limit Exceeded
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findMaxAverage = function (nums, k) {
let maxAverage = 0
if (nums.length === 1) {
return nums[0];
}
for (let i = 0; i <= nums.length - k; i++) {
let sum = 0
for (let j = i; j < k + i; j++) {
sum += nums[j]
}
if (i === 0) {
maxAverage = sum / k
} else {
maxAverage = Math.max(maxAverage, sum / k)
}
}
return maxAverage
}
Solution from others
// using sliding window
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findMaxAverage = function(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++) {
// Subtract the element leaving the window and
// add the new element entering the window.
sum = sum - nums[i - k] + nums[i];
max = Math.max(max, sum);
}
return max / k;
};
Explanation
Start Sum
: First, add up the first 'k' numbers to get a starting sum.Initial Max
: Keep this sum as the initial highest sum.Sliding Window
: Imagine a moving window that covers 'k' numbers in the array.Move Window
: Each time, move the window one number to the right.Update Sum
: Subtract the number that's left behind and add the new number into the sum.Check Max
: Compare the new sum with the highest sum found so far. If it's higher, make this the new highest sum.Repeat
: Keep moving the window and updating the sum until you reach the end of the array.Calculate Average
: Divide the highest sum by 'k' to find the highest average.Done
: Now, you have the highest average of 'k' consecutive numbers.