Maximum Average Subarray


  • 0

    Click here to see the full article post


  • 0
    C

    A slight performance improvement: avoid division until the return statement. In other words just keep a sliding window of the sum of k elements and return max-sum / k.


  • 0
    C

    Also the first math.max is not necessary since the test is any number vs the smallest possible number.


  • 0

    @chris24e Thanks for your suggestion. I have updated the code.


  • 0
    C

    Same suggestion as chris but for Approach# 2


  • 0
    H

    the last answer is so good


  • 0
    H

    Thanks for your suggestion. I have updated the code.


  • 0
    2

    ?!!? I don't understand the question. why isn't it interpreted as sum the k highest int in the array then divide k?


  • 0
    P

    easy to understand Java Solution

    class Solution {
        public double findMaxAverage(int[] nums, int k) {
            
            if (nums.length == 1)return (double)nums[0];                      
            double max = Integer.MIN_VALUE;
            
            loop1:
            for (int i=0;i<nums.length;i++){
                int sum = nums[i];
                for (int j=i+1;j<i+k;j++){
                    if (j>=nums.length)break loop1;
                    sum = sum + nums[j];                                                
                }
                double average = (double)sum/k;
                if (average>max){
                    max = average;
                }                        
            }
            return max;
            
            
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.