Code Signal_练习题_arrayMaxConsecutiveSum

Posted yd2018

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Code Signal_练习题_arrayMaxConsecutiveSum相关的知识,希望对你有一定的参考价值。

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
膜拜大佬

 

以上是关于Code Signal_练习题_arrayMaxConsecutiveSum的主要内容,如果未能解决你的问题,请参考以下文章

Code Signal_练习题_Minesweeper

Code Signal_练习题_stringsRearrangement

Code Signal_练习题_firstDigit

Code Signal_练习题_digitDegree

Code Signal_练习题_matrixElementsSum

Code Signal_练习题_alphabeticShift