题目:
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].
class Solution {
public double findMaxAverage(int[] nums, int k) {
//给定数组,找出连续的子串(其中平均值最大),返回该最大的子串平均值
//思路:使用PreSum求解
int [] preSum=new int[nums.length];
preSum[0]=nums[0];
//求和
for(int i=1;i<nums.length;i++){
preSum[i]=nums[i]+preSum[i-1];
}
//求解
//初始k个元素和
int max=preSum[k-1];
for(int i=k;i<nums.length;i++){
int temp=preSum[i]-preSum[i-k];
max=Math.max(max,temp);
}
return max/1.0/k;
}
}