leetcode-cn Daily Challenge on Febrary 4th, 2021.
Difficulty : Easy
Related Topics : Array
Given an array consisting of
n
integers, find the contiguous subarray of given lengthk
that has the maximum average value. And you need to output the maximum average value.Input: [1,12,-5,-6,50,3], k = 4 Output: 12.75 Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
- 1 <=
k
<=n
<= 30,000.- Elements of the given array will be in the range [-10,000, 10,000].
- mine
- Java
Runtime: 4 ms, faster than 41.39%, Memory Usage: 98.5 MB, less than 6.41% of Java online submissions
public double findMaxAverage(int[] nums, int k) { int left = 0, right = 0; double sum = 0; while (right - left < k) { sum += nums[right++]; } double ans = sum; while (right < nums.length) { sum += nums[right++] - nums[left++]; ans = Math.max(ans, sum); } return ans / k; }
- Java