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].
这道题可以用双指针,也可以用猥琐算法。这里都给出来
public class Solution {
public double findMaxAverage(int[] nums, int k) {
if(nums.length == 1) return nums[0];
int h= 0;
int max = Integer.MIN_VALUE;
for(int i=k-1;i<nums.length;i++){
int tmp = sum(nums,h,i);
if(tmp>max){
max = tmp;
}
h++;
}
return (double)max/k;
}
public int sum(int[] nums,int start,int end){
int res =0;
for(int i=start;i<=end;i++){
res += nums[i];
}
return res;
}
}
public class Solution {
public double findMaxAverage(int[] nums, int k) {
if(nums.length == 1) return nums[0];
int max = 0;
for(int i=0;i<k;i++){
max += nums[i];
}
int tmp =max;
for(int i=k;i<nums.length;i++){
tmp = tmp + nums[i] - nums[i-k];
if(tmp>max){
max = tmp;
}
}
return (double)max/k;
}
}
微信扫一扫
支付宝扫一扫