Sliding Window Fixed-size window
180. Maximum Average Subarray I
You are given an array of integers nums and an integer k. Look at every subarray of exactly k
elements, and return the largest average among them.
A subarray is a contiguous sequence of elements from nums. The average of k numbers is their sum
divided by k, so it can have a fractional part.
The answer is a floating-point number, and different correct ways of computing it can round differently in the last digits. So an answer counts as right when it is within 10−6 of the expected answer, or, for an expected answer larger than 1 in absolute value, within 10−6 times that answer.
Example 1
Input: nums = [5, -3, 8, 2, -4, 9, 6], k = 4
3.75Explanation: The four subarrays of length 4 add up to 12, 3, 15 and 13. The best one is [8,2,-4,9], and its
average is 15 / 4 = 3.75.
Example 2
Input: nums = [-7, -2, -9, -4, -1], k = 2
-2.5Explanation: Every pair of neighbours has a negative sum. The pair [-4,-1] loses the least, and its average is
−5 / 2 = −2.5.
Example 3
Input: nums = [7, 0, -2, 4, 1, 0, 3, 1], k = 8
1.75Explanation: Here k is the length of the array, so the only subarray is the whole array. Its sum is 14, and 14 / 8 = 1.75.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 1091 ≤ k ≤ nums.length
Clarifying questions
What you would ask an interviewer before writing any code.