Maximum Average Subarray I - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
💡 Note: Maximum average subarray is [12,-5,-6,50] with sum 51 and average 51/4 = 12.75
Example 2 — Small Array
$ Input: nums = [5], k = 1
Output: 5.00000
💡 Note: Only one element, so maximum average is 5.0
Example 3 — All Negative
$ Input: nums = [-1,-2,-3,-4], k = 2
Output: -1.50000
💡 Note: Best subarray is [-1,-2] with average -3/2 = -1.5

Constraints

  • n == nums.length
  • 1 ≤ k ≤ n ≤ 105
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Maximum Average Subarray I: Find Best k-Length WindowInput:112-5-6503k = 4Process: Check all windows of length 4Window 1: avg = 0.5Window 2: avg = 12.75Window 3: avg = 10.5Output: Maximum average = 12.7512.75
Understanding the Visualization
1
Input
Array nums and window size k
2
Process
Find all subarrays of length k and calculate averages
3
Output
Return maximum average found
Key Takeaway
🎯 Key Insight: Use sliding window to avoid recalculating the entire sum for each window - just add the new element and subtract the old one
Asked in
Google 32 Amazon 28 Microsoft 15
185.0K Views
Medium Frequency
~15 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen