您的位置 首页 JAVA(2017)

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

这道题可以用双指针,也可以用猥琐算法。这里都给出来

public class Solution {
    public double findMaxAverage(int[] nums, int k) {
        if(nums.length == 1) return nums[0];
        int h= 0;
        int max = Integer.MIN_VALUE;
        for(int i=k-1;i<nums.length;i++){
            int tmp = sum(nums,h,i);
            if(tmp>max){
                max = tmp;
            }
            h++;
        }
        return (double)max/k;
        
    }
    public int sum(int[] nums,int start,int end){
        int res =0;
        for(int i=start;i<=end;i++){
            res += nums[i];
        }
        return res;
    }
}

 

public class Solution {
    public double findMaxAverage(int[] nums, int k) {
        if(nums.length == 1) return nums[0];
        int max = 0;
        for(int i=0;i<k;i++){
            max += nums[i];
        }
        int tmp =max;
        for(int i=k;i<nums.length;i++){
            tmp = tmp + nums[i] - nums[i-k];
            if(tmp>max){
                max = tmp;
            }

        }
        return (double)max/k;
        
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《643. Maximum Average Subarray I》

发表评论

邮箱地址不会被公开。

返回顶部