Maximum Average Subarray I - Problem

You are given an integer array nums consisting of n elements, and an integer k. Your task is to find a contiguous subarray whose length is exactly k that has the maximum average value.

Think of it like finding the best performing streak in a series of scores! For example, if you have test scores [1, 12, -5, -6, 50, 3] and want to find the best 4 consecutive scores, you'd calculate averages for each possible group of 4 and return the highest one.

Goal: Return the maximum average value as a floating-point number.

Note: Any answer within 10-5 of the actual answer will be accepted.

Input & Output

example_1.py โ€” 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.py โ€” Single Element
$ Input: nums = [5], k = 1
โ€บ Output: 5.00000
๐Ÿ’ก Note: Only one subarray possible: [5] with average 5.0
example_3.py โ€” All Negative
$ Input: nums = [-1,-2,-3,-4], k = 2
โ€บ Output: -1.50000
๐Ÿ’ก Note: Maximum average subarray is [-1,-2] with sum -3 and average -3/2 = -1.5

Constraints

  • n == nums.length
  • 1 โ‰ค k โ‰ค n โ‰ค 105
  • -104 โ‰ค nums[i] โ‰ค 104
  • k is always valid (k โ‰ค length of array)

Visualization

Tap to expand
Sliding Window Maximum Average112-5-6503Window 1: Sum = 2, Avg = 0.50Window 2: Sum = 51, Avg = 12.75 โœ“Window 3: Sum = 42, Avg = 10.50Maximum Average Found: 12.75Time Complexity: O(n) | Space Complexity: O(1)O(nk)Brute Forceโ†’O(n)Sliding Window
Understanding the Visualization
1
Initialize Window
Calculate sum of first k elements to establish our baseline
2
Slide and Update
Move window right: subtract outgoing element, add incoming element
3
Track Maximum
Keep track of the highest sum encountered during sliding
4
Return Average
Divide the maximum sum by k to get the maximum average
Key Takeaway
๐ŸŽฏ Key Insight: The sliding window technique transforms an O(n*k) problem into O(n) by maintaining a running sum and updating it incrementally rather than recalculating from scratch.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
73.9K Views
High Frequency
~15 min Avg. Time
1.8K 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