20180723剑指offer题31——连续子数组的最大和

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41819299/article/details/81174340

一、要求

输入一个整型数组,数组值有正有负,举个例子

输入:[1, -2, 3, 10, -4, 7, 2, -5]

其中的连续子数组3,10,-4,7,2  得到最大和18

二、思路及代码

这个数组有正有负,那么最大和至少为正数,有点赌徒心态:

(1)假设一段连续子数组的和是正数,那么就有涨的希望,下一个是正是负没关系,都先存起来

(2)假设一段连续子数组的和是负数,跌停了,不要了

(3)每来一个新数字,计算一下连牌和,看看要不要换新的最大和max

旧的正current+正数>正数>旧的负current+正数

用两个变量,res存储目前为止的最大和,current存储现在赌徒的和

current为正:res=max(res,crrrent+new)

current为负:res=max(res,new)

def max_sum(a):
    current=0
    res=float("-inf")
    for new in a:
        if current<=0:
            current=new

        else:
            current+=new
        res=max(res,current)
    return res


a= [1, -2, 3, 10, -4, 7, 2, -5]
print(max_sum(a))

三、运行结果

18

  

四、思考与总结

1.python的无穷

Python中可以用如下方式表示正负无穷: float("inf"), float("-inf") 

猜你喜欢

转载自blog.csdn.net/weixin_41819299/article/details/81174340