Introduction
The Maximum Average Subarray I problem asks us to find the contiguous subarray of exactly k elements that has the highest average.
Since every possible subarray has the same length k, we can efficiently solve the problem using the Sliding Window technique.
Problem Statement
Given an integer array nums and an integer k, find a contiguous subarray of length k that has the maximum average.
Return the maximum average.
Example
Input:nums = [1, 12, -5, -6, 50, 3]
k = 4
Output:
12.75
Explanation:
The subarray [12, -5, -6, 50] has:
Sum = 12 + (-5) + (-6) + 50 = 51
Average = 51 / 4 = 12.75
Therefore, the maximum average is 12.75.
Constraints
- 1 ≤ k ≤ n
- n = nums.length
- 1 ≤ n ≤ 10⁵
- -10⁴ ≤ nums[i] ≤ 10⁴
- The answer should be accurate within 10⁻⁵.
Premium Video
This video is available to Premium members or users who have purchased the course.
Sign in to UnlockApproach 1: Brute Force
Explanation
We can check every possible subarray of length k.
For each starting position:
- Calculate the sum of the next k elements.
- Calculate their average.
- Compare it with the current maximum average.
- Continue until all possible subarrays are checked.
Since we calculate the sum of k elements for every window, this approach takes O(n × k) time.
Steps
- Start from the first possible index.
- Calculate the sum of k consecutive elements.
- Calculate the average.
- Update the maximum average.
- Move to the next starting position.
- Repeat until all windows are processed.
Dry Run
nums = [1, 12, -5, -6, 50, 3]k = 4
Window 1:
[1, 12, -5, -6]
Sum = 2
Average = 0.5
Window 2:
[12, -5, -6, 50]
Sum = 51
Average = 12.75
Window 3:
[-5, -6, 50, 3]
Sum = 42
Average = 10.5
Maximum Average = 12.75
Brute Force Code
Complexity Analysis
Time Complexity: O(n × k)
Space Complexity: O(1)
Approach 2: Optimized Solution Using Sliding Window
Explanation
The brute-force approach calculates the complete sum for every window.
Instead, we can reuse the previous window's sum.
When the window moves one position:
- Add the new element entering the window.
- Remove the element leaving the window.
This updates the sum in O(1) time.
Steps
- Calculate the sum of the first k elements.
- Store it as the maximum sum.
- Move the window one position at a time.
- Add the new element.
- Remove the outgoing element.
- Update the maximum sum.
- Divide the maximum sum by k.
Dry Run
nums = [1, 12, -5, -6, 50, 3]k = 4
Initial Window:
[1, 12, -5, -6]
Sum = 2
Maximum Sum = 2
Slide Window:
Add 50
Remove 1
New Window:
[12, -5, -6, 50]
Sum = 2 + 50 - 1 = 51
Maximum Sum = 51
Slide Window:
Add 3
Remove 12
New Window:
[-5, -6, 50, 3]
Sum = 51 + 3 - 12 = 42
Maximum Sum = 51
Maximum Average:
51 / 4 = 12.75
Optimized Code