文章

67

粉丝

207

获赞

29

访问

36.7k

头像
最大连续子序列 题解:Python,对于负数严防死守,对于全负数中间加0 的尽力提取

while True:
    try:
        n = int(input())
        if n == 0:
            break
        num = list(map(int,input().split()))
        maxSum = 0
        thisSum = 0
        indexFront = 0
        indexFront2 = 0
        indexLast = 0
        index = 0
        for i in range(0,n):
            if thisSum == 0:
                indexFront = i
            thisSum = thisSum + num[i]
            if thisSum < 0:#如果是负数就不记录了
                thisSum = 0
                continue
            if maxSum < thisSum|(maxSum==0&thisSum==0):#两种情况,第一种是正常记录,第二种是对于前面都是负数,这次到0的记录
                index = 1#都是负数到不了这一步
                maxSum = thisSum
                indexFront2 = indexFront
                indexLast = i
        if index == 0:#对于都是负数的情况
            print(0,end=' ')
            print(num[0],end = ' ')
            print(num[n-1])
        else:
            print(maxSum,end=' ')
            print(num[indexFront2],end=' ')
            print(num[indexLas...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发