Description
Given an integer array nums consisting of n elements and an integer k, find a contiguous subarray of length k that has the maximum average value. Return the maximum average.
Examples
Input:
nums = [1,12,-5,-6,50,3], k = 4Output:
12.75Explanation:
Average of [12,-5,-6,50] is 12.75.
Input:
nums = [-1, -2, -3, -4, -5], k = 3Output:
-2Explanation:
When all numbers are negative, the subarray with the least negative sum is the answer. The subarray [-1,-2,-3] has sum -6 with average -2.0, which is the maximum among all possible subarrays of length 3.
Input:
nums = [7, 4, 5, 8, 2, 3, 1, 4, 2], k = 5Output:
5.2Explanation:
Checking all subarrays of length 5: [7,4,5,8,2] has sum 26 and average 5.2, [4,5,8,2,3] has sum 22 and average 4.4, [5,8,2,3,1] has sum 19 and average 3.8. The maximum average is 5.2.
Constraints
- •
1 ≤ k ≤ nums.length ≤ 10⁵