Given an array with positive and negative numbers, find the maximum average subarray
which length should be greater or equal to given length k
.
Example
Example 1:
Input:
[1,12,-5,-6,50,3]
3
Output:
15.667
Explanation:
(-6 + 50 + 3) / 3 = 15.667
Example 2:
Input:
[5]
1
Output:
5.000
Notice
It's guaranteed that the size of the array is greater or equal to k.
思路:直接求,不要计算,那么我们发现题目要求最大值,并且average的长度> k,那么我们先不管长度,我们先问,subarray(i,j)能够求的最大值会是多少;
(ai + .. + aj) / (j-i+1) >= avg,这个是否成立,那么转换为(ai - avg) + .. ( aj - avg) >=0
那么问题转换为B[i] 组数里面,有没有B[j] - B[i] , j - i + 1 >= k 也就是 i <= j - k + 1; 能否找到一段区间和 >= 0, 并且j - i + 1 >= k;
那么就是一个解空间的搜索问题了,上面的B数组可以写成了一个canAverage的函数,那么就是一个区间搜索问题,把求最大的average, 变换成,我给定一个average,能够找到 [i, j] 区间>= 0; 能找到,start = mid;,因为是求最大的average,一直往上找。
搜索的区间是[minAi, maxAi]
class Solution {
public double findMaxAverage(int[] nums, int k) {
if(nums == null || nums.length == 0) {
return 0.0;
}
int min = nums[0];
int max = nums[0];
for(int i = 1; i < nums.length; i++) {
min = Math.min(min, nums[i]);
max = Math.max(max, nums[i]);
}
double start = min; double end = max;
double eps = 1e-5;
while(start + eps < end) {
double mid = start + (end - start) / 2;
if(canfind(mid, nums, k)) {
start = mid;
} else {
end = mid;
}
}
if(canfind(end, nums, k)) {
return end;
}
return start;
}
private boolean canfind(double avg, int[] nums, int k) {
double rightsum = 0.0;
double leftsum = 0.0;
double minleftsum = 0.0;
// 先算[0,k-2];
for(int j = 0; j < k - 1; j++) {
rightsum += nums[j] - avg;
}
// 从第k-1开始算;也就是满足第k个了;
for(int j = k - 1; j < nums.length; j++) {
rightsum += nums[j] - avg;
if(rightsum - minleftsum >= 0) {
return true;
}
// j - i + 1 >= k 推出来: i <= j - k + 1;
leftsum += nums[j - k + 1] - avg;
minleftsum = Math.min(minleftsum, leftsum);
}
return false;
}
}