Maximum Average Subarray II - Problem

You are given an integer array nums consisting of n elements, and an integer k.

Find a contiguous subarray whose length is greater than or 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 length 4, giving average 51/4 = 12.75
Example 2 — Minimum Length
$ Input: nums = [5], k = 1
Output: 5.00000
💡 Note: Only one element, so the subarray [5] has average 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 (-1-2)/2 = -1.5

Constraints

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

Visualization

Tap to expand
Maximum Average Subarray IIInput Array (k=4):112-5-6503Candidate Subarrays (length ≥ 4):[12,-5,-6,50] avg=12.75 ✓[1,12,-5,-6,50] avg=10.4[12,-5,-6,50,3] avg=10.8Find subarray with length ≥ k having maximum averageMaximum Average: 12.75
Understanding the Visualization
1
Input
Array [1,12,-5,-6,50,3] and k=4
2
Process
Find all subarrays length ≥ 4 and calculate averages
3
Output
Return maximum average found: 12.75
Key Takeaway
🎯 Key Insight: Binary search on the answer space is more efficient than checking all subarrays directly
Asked in
Google 35 Facebook 28 Amazon 22
78.0K Views
Medium Frequency
~35 min Avg. Time
892 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