Passed 55/74 test cases -- TLE Java Simple Solution


  • -1
    M
    public double findMaxAverage(int[] nums, int k) { 
        double max=0, avg=0;
        if (k == 1 && nums.length == 1) 
            return nums[0];
            
        if (k == nums.length)
            return maxAverage(nums, k);
            
        for (int i=k; i<nums.length; i++) {
             avg = maxAverage(nums, i);
             max = Math.max(avg, max);
        }
            
        return max;
      }
        
      public static double maxAverage(int[] nums, int k) {
    	double sum = nums[0];
    	for (int j = 1; j < k; j++)
    	      sum += nums[j];
    
    	double maxSum = sum;
    	for (int i = k; i < nums.length; i++) {
    		// slide the window
    		// add current element and remove prev first element
    		sum = sum + nums[i] - nums[i - k];
    		maxSum = Math.max(sum, maxSum);
    	}
    
    	return maxSum / k;
    }
    

Log in to reply
 

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