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].
这道题一开始直接想到了python切片操作,虽然很简答,但是超时了
然后就利用传统思路解决,加一个减一个的思想,整个list只遍历一次。
class Solution(object):
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
max = tmp = sum(nums[0:k])
for i in range(k,len(nums)):
tmp = tmp + nums[i] -nums[i-k]
if tmp > max:
max = tmp
return float(max)/float(k)
这个方法时间还是很长,所以看了下别人的解决方法:
Using prefix sums (where sums[i] is the sum of the first i numbers) to compute subarray sums.
def findMaxAverage(self, nums, k):
sums = [0] + list(itertools.accumulate(nums))
return max(map(operator.sub, sums[k:], sums[:len(sums)-k])) / k
NumPy version (requires import numpy as np):
def findMaxAverage(self, nums, k):
sums = np.cumsum([0] + nums)
return int(max(sums[k:] - sums[:-k])) / k
这两个答案起初不是很懂,所以先补充下相关知识:
accumulate
accumulate迭代器(Python3 中提供)返回累加之和或者两个函数(开发者可以传递给accumulate)的累计结果,accumulate的默认操作是相加,如下,首先我们引入accumulate方法,然后传递给它0-9这个序列,它就会将它们依次相加,例如第一个是0,第二个是0+1,第三个是1+2,等等;
>>> from itertools import accumulate
>>> list(accumulate(range(10)))
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
下面我们引入operator模块,我们首先将数字1-4传递给accumulate迭代器,另外又将operator.mul传递给它,它接受这个函数用于相乘。所以每次迭代,它相乘而非是相加(1 * 1 = 1,1 * 2 = 2,2 * 3 = 6,等等)。
>>> from itertools import accumulate
>>> import operator
>>> list(accumulate(range(1,5),operator.mul))
[1, 2, 6, 24]
numpy.cumsum
>>> a = np.array([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> np.cumsum(a)
array([ 1, 3, 6, 10, 15, 21])
>>> np.cumsum(a, dtype=float) # specifies type of output value(s)
array([ 1., 3., 6., 10., 15., 21.])
>>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
array([[1, 2, 3],
[5, 7, 9]])
>>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
array([[ 1, 3, 6],
[ 4, 9, 15]])
所以这两个方法思路是一样的,先把nums里面的数值迭代相加生成一个list。然后求得每k个数相加的最大值。