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;
            
            
        }
    }

  • 0
    D

    Sliding window approach in swift.

    class Solution {
        func findMaxAverage(_ nums: [Int], _ k: Int) -> Double {
            if nums.count == 0 {
                return 0
            }
            if nums.count <= k {
                return Double(nums.reduce(0, +)) / Double(k)
            }
            var leftPointer = 0
            var rightPointer = k - 1
            var runningSum = nums[leftPointer...rightPointer].reduce(0, +)
            var maxSum = runningSum
            while(rightPointer < nums.count - 1) {
                rightPointer += 1
                runningSum = runningSum - nums[leftPointer] + nums[rightPointer]
                maxSum = max(maxSum, runningSum)
                leftPointer += 1
            }
            return (Double(maxSum) / Double(k))
        }
    }

Log in to reply
 

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