Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4 Output: 12.75 Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note:
- 1 <=
k<=n<= 30,000. - Elements of the given array will be in the range [-10,000, 10,000].
This problem can be solved using either a two-pointer approach or a more subtle algorithm. Both methods are provided here.
public class Solution { public double findMaxAverage(int[] nums, int k) { if(nums.length == 1) return nums[0]; int h= 0; int max = Integer.MIN_VALUE; for(int i=k-1;imax){ max = tmp; } h++; } return (double)max/k; } public int sum(int[] nums,int start,int end){ int res =0; for(int i=start;i<=end;i++){ res += nums[i]; } return res; } }
public class Solution { public double findMaxAverage(int[] nums, int k) { if(nums.length == 1) return nums[0]; int max = 0; for(int i=0;imax){ max = tmp; } } return (double)max/k; } } This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:
Original author:Jake Tao,source:「643. Maximum Average Subarray I」