Dynamic Programming / sliding window


  • 0
    T

    Easy Steps

    1. Calculate the sum unto K nodes
    2. Drop the tail and add the next node to the result
    3. Compare the current with that last biggest result
       
        public double findMaxAverage(int[] nums, int k) {
            double result = 0;
            for (int i=0; i<k;i++){
                result+=nums[i];
            }
            double prev = result;
    
            for (int j=k; j< nums.length; j++){
                double newResult = prev - nums[j-k] + nums[j];
                if (newResult > result){
                    result  = newResult;
                }
                prev = newResult;
            }
    
            return result/k;
        }
    
    

Log in to reply
 

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