Given an arrays consisting n of integers, find the contiguous subarray of Given length that have the k maximum Avera GE value. And you need to output the maximum average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4output:12.75explanation:maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note:
- 1 <=
k <= n <= 30,000.
- Elements of the given array would be in the range [-10,000, 10,000].
Title tag: Array
The topic gives us a nums array and a K, let's find a subarray of length k, its average value is the largest.
The easy way to think of this is to sliding window, imagine that there is a windows with a length of k moving, add a new num each time, and subtract an old num. Maintains a maximum sum of updates. (There is no need for each maintenance update at the time/K, the last/k will be)
Finally, use the biggest sum/k.
In the process of doing this problem, I found that double.min_value is actually more than 0 figures. The integer.min_value used before is clearly the smallest negative number.
Take a look at the definition of Double.min_value: A constant holding the smallest positive nonzero VALUE double of type, 2-1074.
Java Solution:
Runtime beats 51.3%
Completion Date: 10/19/2017
Keywords: Array
Key point: Sliding Window
1 classSolution2 {3 Public DoubleFindmaxaverage (int[] Nums,intk)4 {5 DoubleMav =-Double.max_value;6 DoubleTempmav = 0;7 8 for(inti=0; i<nums.length; i++)9 {TenTempmav + =Nums[i]; One A if(i + 1 >=k) - { -Mav =Math.max (MAV, TEMPMAV); theTempmav-= nums[i + 1-K]; - } - - } + - + returnMAV/K; A } at}
Reference: N/A
Leetcode List of topics- leetcode Questions List
Leetcode 643. Maximum Average Subarray I (one of the maximum mean Subarray)