博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Code Signal_练习题_arrayMaxConsecutiveSum
阅读量:7065 次
发布时间:2019-06-28

本文共 957 字,大约阅读时间需要 3 分钟。

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

 

转载于:https://www.cnblogs.com/BlameKidd/p/9490801.html

你可能感兴趣的文章
LEFT JOIN、RIGHT JOIN、INNER JOIN、FULL JOIN 使用
查看>>
谈谈 oc原生和跳转h5 页面 来回切换的功能
查看>>
【二维树状数组】【CF10D】 LCIS
查看>>
Hive基础知识
查看>>
解决windows系统80端口被占用问题
查看>>
redis基础和sentinel
查看>>
改变ubuntu终端显示语言(桌面系统是中文,终端提示是英文)
查看>>
13.scrapy框架的日志等级和请求传参
查看>>
linux 打开FTP 功能
查看>>
rollout
查看>>
上传图片前判断图片的尺寸
查看>>
dm8148 开发之---IDR帧
查看>>
电子自旋
查看>>
weka中算法说明[转]
查看>>
leetcode — plus-one
查看>>
less语法小结
查看>>
人人贷网的数据爬取
查看>>
索引选择性与cardinality
查看>>
如何处理变频器对PLC模拟量干扰?
查看>>
团队项目 第一次作业
查看>>