Maximum Average Subarray I
Maximum Average Subarray I
Problem Statement
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.
Example
Input: nums = [1,12,-5,-6,50,3], k = 4
nums: [1, 12, -5, -6, 50, 3], k: 4
Output: 12.75
Output: 12.75000
The subarray [12, -5, -6, 50] has the maximum average of (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75.
Solution
The problem can be solved using a fixed-size sliding window. We calculate the sum of the first `k` elements. Then, we slide the window one element at a time, updating the sum by subtracting the element that is leaving the window and adding the new element that is entering. We keep track of the maximum sum found so far.
Algorithm Steps
- Calculate the sum of the first `k` elements.
- Initialize `maxSum` with this initial sum.
- Iterate from the `k`-th element to the end of the array.
- Update the current sum by adding the current element and subtracting the element that is `k` positions behind.
- Update `maxSum` with the maximum of `maxSum` and the current sum.
- The result is `maxSum / k`.
Maximum Average Subarray
Fixed-Size Sliding Window
Ready to start the visualization
nums
Current Sum
Max Sum