leetcode-Arrays-findMaxAverage

题目:643. Maximum Average Subarray I

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 double findMaxAverage(int[] nums, int k) {
		  int length = nums.length;
		  double sum;
		  double average;
		  double maxAverage = -10000;
		  for(int i = 0; i <=length-k; i++) {
			  sum = 0;
			  for (int j = i; j < i+k; j++) {
				  sum = sum+nums[j];
			  }
			  average = sum/k;
			  if(average > maxAverage)
				  maxAverage = average;
			  
		  }
		  return maxAverage;
	  }

官方答案

不是先创建一个累积和数组,然后遍历它来确定所需的和,
我们只需遍历一次num,然后继续确定k长度子数组的可能和。
为了理解这个想法,假设我们已经知道了从索引i到索引i+k的元素之和,假设它是x。
现在,要确定从索引i+1到索引i+k+1的元素之和,我们需要做的就是从x减去元素nums[i],然后将元素nums[i+k+1]添加到x。
我们可以根据这个想法来执行我们的过程,并确定可能的最大平均值。

Complexity Analysis
Time complexity : O(n)O(n). We iterate over the given numsnums array of length nn once only.
Space complexity : O(1)O(1). Constant extra space is used.

    public double findMaxAverage(int[] nums, int k) {
    		        double sum=0;
    		        for(int i=0;i<k;i++)
    		            sum+=nums[i];
    		        double res=sum;
    		        for(int i=k;i<nums.length;i++){
    		            sum+=nums[i]-nums[i-k];
    		                res=Math.max(res,sum);
    		        }
    		        return res/k;
     }

个人理解
以下面这个为例
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

先将前4个捆绑起来,看成一个整体sum,然后依次右移,将右边的数字加进sum来,左边的数字减sum出去,保证连续4个数字

本题的关键在于求连续的子字数组,才能使用捆绑

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值