問題:數組
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.spa
Example 1:code
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:io
k
<= n
<= 30,000.解決:class
① 直接解將數組值相加,當相加的個數超過給定值k時,就減去最前面加上的值(i - k)。記錄最大的和便可。im
public class Solution { //20 ms
public double findMaxAverage(int[] nums, int k) {
double max = Integer.MIN_VALUE; //不能使用Double.MIN_VALUE,不然輸入[-1],1,結果錯誤
double sum = 0;
for (int i = 0;i < nums.length ;i ++ ) {
sum += nums[i];
if(i >= k){
sum -= nums[i - k];
}
if(i >= k - 1 && max <= sum) max = sum; //必須判斷 i >= k - 1,不然結果不正確
}
return max / k;
}
} co
② 先算出前k個數的和,以後計算時加上下一個數,減去第一個數。錯誤
public class Solution { //22ms
public double findMaxAverage(int[] nums, int k) {
int sum = 0;
for(int i = 0;i < k;i ++){
sum += nums[i];
}
int max = sum;
for(int i = 1;i <= nums.length - k;i ++){
sum = sum - nums[i - 1] + nums[i + k - 1];
max = sum > max ? sum : max;
}
return ((double)max) / k;
}
}return