Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.
Example 1:
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
Note: 1 <= k <= n <= 30,000. Elements of the given array will be in the range [-10,000, 10,000].
// sliding window algorithm
class Solution {
public double findMaxAverage(int[] nums, int k) {
double maxAvg = (double)Integer.MIN_VALUE;
double currSum = 0;
int left = 0, right = -1; // right 初始值为 -1 是为了令 nums[0] 被考虑在内
while (true) {
if (right - left + 1 < k) {
right++;
if (right >= nums.length) break;
currSum += nums[right];
} else { // 此时 window size 一定等于 k
maxAvg = Math.max(maxAvg, currSum / k);
currSum -= nums[left];
left++;
}
}
return maxAvg;
}
}
class Solution:
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
preSum = [0] * (len(nums) + 1)
maxAvg = float('-inf')
for i in range(len(nums)):
preSum[i + 1] = preSum[i] + nums[i]
if i >= k - 1:
maxAvg = max(maxAvg, (preSum[i + 1] - preSum[i + 1 - k]) / k)
return maxAvg
class Solution {
public double findMaxAverage(int[] nums, int k) {
int left = 0, right = -1;
long max = Integer.MIN_VALUE;
long window = 0;
while (true) {
while (right - left + 1 < k) {
++right;
if (right >= nums.length) break;
window += nums[right];
}
if (right >= nums.length) break;
max = Math.max(max, window);
window -= nums[left++];
}
return (double)max / k;
}
}