先看个简单的
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].
package l643;
public class Solution {
public double findMaxAverage(int[] nums, int k) {
long sum = 0, max = 0;
for(int i=0; i<k; i++) sum+=nums[i];
max = sum;
for(int i=k; i<nums.length; i++) {
sum += nums[i];
sum -= nums[i-k];
if(sum > max)
max = sum;
}
return (max+0.0)/k;
}
}
Given an array consisting of n
integers, find the contiguous subarray whose length is greater than or equal to 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: when length is 5, maximum average value is 10.8, when length is 6, maximum average value is 9.16667. Thus return 12.75.
Note:
- 1 <=
k
<=n
<= 10,000. - Elements of the given array will be in range [-10,000, 10,000].
- The answer with the calculation error less than 10-5 will be accepted.
思路:有2个trick
1. 只要满足一定误差,所以用二分,直接二分最后的平均值
2. 在判断某个平均值是否满足时,转换为求连续子数组的和大于0(这个求平均值的套路可以记一下)
/*
* 只要10-5 精度就好
*/
public class Solution {
public double findMaxAverage(int[] nums, int k) {
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for(int i : nums) {
min = Math.min(min, i);
max = Math.max(max, i);
}
double lo = min, hi = max;
while(hi-lo > 1e-6) {
double mid = (lo+hi)/2.0;
if(ok(nums, k ,mid))
lo = mid;
else
hi = mid;
}
return lo;
}
private boolean ok(int[] nums, int k, double mid) {
// 数组每个数减去mid,转换为:连续子数组累加大于0
double[] t = new double[nums.length];
for(int i=0; i<nums.length; i++)
t[i] = nums[i] - mid;
double sum = 0;
for(int i=0; i<k; i++) sum += t[i];
if(sum >= 0) return true;
double min = 0, sum2 = 0;
for(int i=k; i<t.length; i++) {
sum2 += t[i-k];
sum += t[i];
min = Math.min(min, sum2);
if(sum - min >= 0) return true;
}
return false;
}
}