Java Sliding Window | Good Efficiency


  • 0
    R
    public class Solution {
        public double findMaxAverage(int[] nums, int k) {
            double runAvg = 0;
            
            if(nums.length == k){
                for(int a: nums) runAvg += a;
                return runAvg/k;
            }
            
            double maxAvg = -99999999;
            for(int i=0; i<k; i++) runAvg += nums[i];
            
            if(runAvg > maxAvg) maxAvg = runAvg;
            
            for(int i=1; i<nums.length-k+1; i++){
                runAvg -= nums[i-1];
                runAvg += nums[i+k-1];
                
                if(runAvg > maxAvg) maxAvg = runAvg;
            }
            
            return maxAvg/k;
            
        }
    }
    

Log in to reply
 

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