644. Maximum Average Subarray II

先看个简单的

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. 1 <= k <= n <= 30,000.
  2. 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. 1 <= k <= n <= 10,000.
  2. Elements of the given array will be in range [-10,000, 10,000].
  3. 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;
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值