标签:分享 size 运行 elements inpu closed nts splay open
Given array of integers, find the maximal possible sum of some of its k
consecutive elements.
Example
For inputArray = [2, 3, 5, 1, 6]
and k = 2
, the output should bearrayMaxConsecutiveSum(inputArray, k) = 8
.
All possible sums of 2
consecutive elements are:
2 + 3 = 5
;3 + 5 = 8
;5 + 1 = 6
;1 + 6 = 7
.8
.
我的解答:
第一种: def arrayMaxConsecutiveSum(inputArray, k): return max([sum(inputArray[i:i + k]) for i in range(len(inputArray))]) 第二种: def arrayMaxConsecutiveSum(inputArray, k): return sorted([sum(inputArray[i:i + k]) for i in range(len(inputArray))])[-1] 这两种虽然都可以运行,但是运行时间太慢了.
def arrayMaxConsecutiveSum(inputArray, k): # return max([sum(inputArray[i:k+i]) for i in range(len(inputArray) - k + 1)]) # too slow, but works s = m = sum(inputArray[:k]) for i in range(k, len(inputArray)): s += inputArray[i] - inputArray[i-k] if s > m: m = s return m
Code Signal_练习题_arrayMaxConsecutiveSum
标签:分享 size 运行 elements inpu closed nts splay open
原文地址:https://www.cnblogs.com/YD2018/p/9490801.html