Code Signal_练习题_arrayMaxConsecutiveSum

时间:2021-03-01 08:02:33

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 be
arrayMaxConsecutiveSum(inputArray, k) = 8.
All possible sums of 2 consecutive elements are:

    • 2 + 3 = 5;
    • 3 + 5 = 8;
    • 5 + 1 = 6;
    • 1 + 6 = 7.
      Thus, the answer is 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

膜拜大佬