Simple java solution


  • 0
    V

    Simple java solution by cumulative sum, beating 96.78%

    public class Solution {
        public double findMaxAverage(int[] nums, int k) {
            if(nums.length < k){
                return -1;
            }
           
            
            for(int i = 1 ; i < nums.length ; i ++) {
                nums[i] = nums[i] + nums[i - 1];
            }
            
            double max = nums[k - 1];
            int j = 0;
            for(int i = k ; i <nums.length ; i ++) {
                if(max < (nums[i] - nums[j])) {
                    max = nums[i] - nums[j] ;
                }
                j ++;
            }
            
            return max / k;
        }
    }
    

Log in to reply
 

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