LeetCode Daily Question 643. Maximum average number of sub-arrays I

643. Maximum average of sub-array I

Given n integers, find the continuous sub-array with the largest average and length k, and output the largest average.

Example:

输入:[1,12,-5,-6,50,3], k = 4
输出:12.75
解释:最大平均数 (12-5-6+50)/4 = 51/4 = 12.75

prompt:

  • 1 <= k <= n <= 30,000。
  • The given data range [-10,000, 10,000].

method one:

  • This question is relatively simple and can be used as an introductory question for "sliding window" and "prefix sum".

Reference code 1: Sliding window

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

Reference code 2: Prefix and

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

Results of the
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_27007509/article/details/113625628