首页 > 试题广场 >

最大序列和

[编程题]最大序列和
  • 热度指数:25438 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
给出一个整数序列S,其中有N个数,定义其中一个非空连续子序列T中所有数的和为T的“序列和”。 对于S的所有非空连续子序列T,求最大的序列和。 变量条件:N为正整数,N≤1000000,结果序列和在范围(-2^63,2^63-1)以内。

输入描述:
第一行为一个正整数N,第二行为N个整数,表示序列中的数。


输出描述:
输入可能包括多组数据,对于每一组输入数据,
仅输出一个数,表示最大序列和。
示例1

输入

5
1 5 -3 2 4

6
1 -2 3 4 -10 6

4
-3 -1 -2 -5

输出

9
7
-1
while True:
    try:
        n=int(input().strip())
        inp=list(map(int,input().strip().split(' ')))
        result=-float('inf')
        index=0
        for i in range(n):
            index+=inp[i]
            result=max(result,index)
            if index<0:
                index=0
        print(result)


    except:
        break
发表于 2019-08-07 20:14:25 回复(0)

是不是快炸了?

try:
    while True:
        num = int(input())
        digits = list(map(int,input().split()))
        temp = 0
        result = float('-inf')
        for i in range(num):
            temp = max(temp+digits[i],digits[i])
            result = max(temp,result)
        print(result)
except Exception:
    pass

图片说明

编辑于 2018-10-09 21:37:14 回复(0)

python2.7 solution。使用python3无法通过。

while True:
    try:
        a, arr = input(), list(map(int, input().split()))
        cur, res = arr[0], arr[0]
        for i in arr[1:]:
            if cur < 0:
                cur = 0
            cur += i
            res = max(res, cur)
        print(res)
    except:
        break
编辑于 2017-10-17 09:39:10 回复(0)
这题没用Python通过的吗?Python为什么一直显示内存超限的错误
while True:
    try:
        n=int(input())
        s=list(map(int,input().split()))
        maxs=s[0]
        temp=0
        for i in range(len(s)):
            temp += s[i]
            if temp>maxs:
                maxs=temp
            if temp<0:
                temp=0
        print(maxs)
    except:
        break

发表于 2017-09-02 22:03:50 回复(1)

问题信息

难度:
4条回答 14985浏览

热门推荐

通过挑战的用户

查看代码