#643
Maximum Average Subarray I
EasyArraySliding WindowSliding WindowArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a sliding window technique to maintain the sum of the current subarray of length k. This allows us to compute the maximum average in linear time by reusing the previous sum.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the sum of the first k elements.
- 2Step 2: Initialize max_avg with the average of the first k elements.
- 3Step 3: Slide the window across the array by adding the next element and removing the first element of the previous window.
- 4Step 4: Update max_avg whenever a new average is greater than the current max_avg.
solution.py9 lines
1# Full working Python code
2
3def findMaxAverage(nums, k):
4 current_sum = sum(nums[:k])
5 max_avg = current_sum / k
6 for i in range(k, len(nums)):
7 current_sum += nums[i] - nums[i - k]
8 max_avg = max(max_avg, current_sum / k)
9 return max_avgℹ
Complexity note: This complexity is O(n) because we only traverse the array once, maintaining a running sum without needing additional space for storing subarrays.
- 1Using a sliding window can significantly reduce the time complexity from O(n²) to O(n).
- 2Maintaining a running sum allows for efficient updates as the window slides.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.