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.輸入一個數組nums和一個整數k。要求找出輸入數組中長度爲k的子數組,而且要求子數組元素的加和平均值最大。返回這個最大的平均值。數組
Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: 最大平均值 (12-5-6+50)/4 = 51/4 = 12.75code
public double findMaxAverage(int[] nums, int k) { double curr = 0; double max = 0; for(int i=0;i<nums.length;i++){ if(i < k){ curr = curr + nums[i]; max = curr; continue; } curr = curr + nums[i] - nums[i-k]; max = (curr > max) ? curr : max ; } return max/k; }