码迷,mamicode.com
首页 > 其他好文 > 详细

Code Signal_练习题_arrayMaxConsecutiveSum

时间:2018-08-17 00:43:42      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:分享   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 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

标签:分享   size   运行   elements   inpu   closed   nts   splay   open   

原文地址:https://www.cnblogs.com/YD2018/p/9490801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!