Solution: Maximum Average Subarray I
Let’s solve the Maximum Average Subarray I using the Sliding Window pattern.
We'll cover the following
Statement
Given an array of integers nums
, and an integer k
, return the maximum average of a contiguous subarray of length k
.
Constraints:
k
nums.length
nums[i]
Solution
The algorithm to find the maximum average of a subarray of length k
uses the sliding window pattern. First, It calculates the sum of the first k
elements of the array and stores them as the current and maximum sum. Then, it slides the window one element at a time over the array. For each new element that enters the window, the algorithm subtracts the element that leaves the window from the current sum and adds the new element to the current sum. This way, the sum of the window elements is calculated without recalculating the entire sum from scratch. The algorithm then updates the maximum sum with the current sum if the value of the current sum is greater than the previously recorded maximum sum. Finally, the algorithm returns the maximum average by dividing the maximum sum with k
.
The algorithm to solve this problem is as follows:
Calculate the sum of the first
k
elements innums
incurrent_sum
.Assign the value of the
current_sum
tomax_sum
to keep a record of the maximum sum.Loop on
nums
from indexk
tillnums.length
and in each iteration of the loop:Update
current_sum
by subtracting the element that leaves the window, i.e.,nums[i - k]
, and adding the new element that just entered the window, i.e.,nums[i]
.Check if the value of
current_sum
is greater than themax_sum
; if so, assign the value ofcurrent_sum
tomax_sum
.
After the loop terminates, return the average of the subarray by dividing
max_sum
withk
.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.