题目
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].
解题思路
计算所有k个连续数的和,求得最大值,平均值
一共有n-k+1个连续k个数,每次用累加求k个连续数的和,需要计算(n-k+1)k次,时间复杂度为O(nk)
考虑到下一个连续k个数的和可以根据上一个连续值的和推出,
sum + nums[j] – nums[j-k]
需要计算(n-k+1)*2次,时间复杂度降为O(n)
代码
func findMaxAverage(nums []int, k int) float64 {
len1 := len(nums)
var sum, maxSum int
for i := 0; i < k; i++ {
sum += nums[i]
}
maxSum = sum
fmt.Printf("sum:%+v\n", sum)
for j := k; j < len1; j++ {
sum = sum + nums[j] - nums[j-k]
if maxSum < sum {
maxSum = sum
}
fmt.Printf("j:%+v, sum:%+v\n", j, sum)
}
return float64(maxSum) / float64(k)
}