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 INPUT nums = [1, 12, -5, -6, 50, 3] 1 i=0 12 i=1 -5 i=2 -6 i=3 50 i=4 3 i=5 Input Values: nums = [1,12,-5,-6,50,3] k = 4 (window size) Find max avg of k=4 elements Window of size 4 ALGORITHM STEPS 1 Init First Window Sum = 1+12+(-5)+(-6) = 2 2 Slide Window Right Add new, remove old element 3 Track Maximum Sum maxSum = max(maxSum, sum) 4 Return Average result = maxSum / k Window Iterations: [1,12,-5,-6] sum=2 avg=0.5 [12,-5,-6,50] sum=51 avg=12.75 [-5,-6,50,3] sum=42 avg=10.5 Max Sum = 51 (window 2) Time: O(n) | Space: O(1) FINAL RESULT Maximum Average Subarray Found: 12 -5 -6 50 Indices: 1 to 4 Calculation: Sum = 12 + (-5) + (-6) + 50 Sum = 51 Avg = 51 / 4 = 12.75 OUTPUT 12.75000 [OK] Answer Verified Error less than 10^-5 Key Insight: The Sliding Window technique avoids recalculating the entire sum for each window position. Instead of O(n*k), we achieve O(n) by adding the new element and subtracting the old one. Formula: newSum = oldSum - nums[i-k] + nums[i] where i is the right edge of the window. TutorialsPoint - Maximum Average Subarray I | Sliding Window Approach
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