Maximum Average Subarray I
1 approach, code in every language
Problem description
You are given an array of integers and a fixed length k. Consider every contiguous block of exactly k consecutive elements and compute the average of each block.
Return the largest average found among all such blocks. Answers within a tiny numerical tolerance of the true maximum are accepted.
Example 1
Input: nums = [1, 12, -5, -6, 50, 3], k = 4
Output: 12.75
The window [12, -5, -6, 50] sums to 51, and 51 / 4 = 12.75, which beats every other length-4 window.
Example 2
Input: nums = [4, 0, 4], k = 2
Output: 2.00000
The two length-2 windows are [4, 0] and [0, 4], both averaging 2. The maximum average is 2.
Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Warmest Run of Days is our own problem on the technique behind Maximum Average Subarray I: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free