Sliding window Solution- Java


  • 0
    Z
    public double findMaxAverage(int[] nums, int k) {
            if(nums==null || nums.length==0 || nums.length<k) return 0.0;
            double max =  Integer.MIN_VALUE, sum=0,n=0;
            int j=0;
            for(int i=0; i<nums.length; i++){
                n++;
                sum += nums[i];
                    if(n==k) {
                        max = Math.max(max, sum/n);
                        sum-=nums[j];
                        j++;
                        n--;
                    }
            }
            return max;
        }
    

Log in to reply
 

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