原题是:
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].
思路1:
第一个思路就是直接遍历,求子数组的和。但是超时。
代码1:
值得注意的是,要注意遍历时,循环变量的终值,不要越界。切片的index虽然是i + k,但是实际上取不到它,最多仍然是i+ k -1,所以不会越界。
思路2:
第二个思路就是,去头,加尾,以得到新的子数组的和,减少了时间复杂度。
代码2:
class Solution:
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
sums = sum(nums[0:k])
curSum = sums
for i in range(1 , (len(nums) - k + 1)):
curSum = curSum + nums[i+k-1]-nums[i-1]
sums = max(sums , curSum)
return float(sums)/float(k)
这一类题,往往是一个变量存随着遍历实时变化的量,一个变量更新最大(小)值。