LeetCode——643. Maximum average number of sub-arrays I

Title description:

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

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

Example:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average (12-5-6+50)/4 = 51/4 = 12.75

code show as below:

class Solution {
    
    
    public double findMaxAverage(int[] nums, int k) {
    
    
        int n = nums.length;
        int left = 0, right = 0;
        double ans = 0;
        for (int i = 0; i < k; i++) {
    
    
            ans += nums[i];
        }
        double m = ans / k;
        while (right < n) {
    
    
            if (right - left == k) {
    
    
                ans = ans - nums[left] + nums[right];
                left++;
            }
            right++;
            m = Math.max(m, ans / k);
        }
        return m;
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/113624494