findMaxAverage-Maximum average of sub-array I

Subject requirements

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

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

prompt:

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

Problem-solving ideas

This question is
a simple question 1. Record the maximum value of a variable maxsun, which is used to store the maximum value in all windows (it will be updated as the window moves)
2. Record a variable sumIn to record the sum of the current window
3. If the sum of step 2 Is greater than the value of step 1, then update 1
4. Use maxsum/k to get the result

Code demo

class Solution {
    
    
    public double findMaxAverage(int[] nums, int k) {
    
    
        //存放最大的数据
       int maxsum=0;
        for (int i = 0; i < k; i++) {
    
    
            maxsum+=nums[i];
        }
        int sumIn=maxsum;
        for(int j=k;j<nums.length;j++)
        {
    
    
            sumIn=sumIn-nums[j-k]+nums[j];
            maxsum=sumIn>maxsum ?sumIn:maxsum;
        }
        double res;
        res=maxsum*1.0/k;
        return res;

    }
}

Demonstration effect

The info
answer was successful:
execution time: 2 ms, defeating 100.00% of Java users
Memory consumption: 42.7 MB, defeating 54.41% of Java users

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/113626581