Sliding window

Maximum Average Subarray I

Estimated reading: 1 minute 33 views

You are given an integer array nums consisting of n elements, and an integer k.

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.

Examples

  • Example 1:

    • Input: nums = [1, 12, -5, -6, 50, 3], k = 4
    • Output: 12.75000
    • Explanation: The maximum average is calculated from the subarray [12, -5, -6, 50]. 12−5−6+504=514=12.75\frac{12 – 5 – 6 + 50}{4} = \frac{51}{4} = 12.75
  • Example 2:

    • Input: nums = [5], k = 1
    • Output: 5.00000
    • Explanation: Since the array has only one element and k = 1, the maximum average is simply 5.
				
					int left=0;
    double maxAverage = Double.NEGATIVE_INFINITY;;
    int currrentWindowsK  =0;
    double currentTotal = 0 ;
    public double findMaxAverage(int[] nums, int k) {
        //preparea window
        for(int right =0;right<nums.length;right++){
            currentTotal += nums[right];
            currrentWindowsK++;
            while(currrentWindowsK==k){
                
                maxAverage = Math.max(maxAverage, currentTotal/k);
                currentTotal-=nums[left];
                left++;
                currrentWindowsK--;

            }
        }
        return maxAverage;
    }
				
			
Share this Doc

Maximum Average Subarray I

Or copy link

CONTENTS