求所有子数组的和的最大值

# -*- coding:utf-8 -*-

'''
连续子数组的最大和
限定语言:Kotlin、Typescript、Python、C++、Groovy、Rust、C#、Java、Go、C、Scala、Javascript、Ruby、Swift、Php、Python 3
输入一个长度为n的整型数组array,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
数据范围:
1 <= n <= 10^51<=n<=105

-100 <= a[i] <= 100−100<=a[i]<=100


要求:时间复杂度为 O(n)O(n),空间复杂度为 O(n)O(n)
进阶:时间复杂度为 O(n)O(n),空间复杂度为 O(1)O(1)

示例1
输入
[1,-2,3,10,-4,7,2,-5]
输出
18
说明
经分析可知,输入数组的子数组[3,10,-4,7,2]可以求得最大和为18
示例2
输入
[2]
输出
2
示例3
输入
[-10]
输出
-10
'''

def max(array):
temp,max=array[0],array[0]
i,j=1,len(array)
for i in range(1,j):
if array[i]+temp>=array[i]:
temp=array[i]+temp
else:
temp=array[i]

if temp > max:
max=temp

return max

if __name__=="__main__":
alist = [-3,4,-4,2,6,-5,4]
max=max(alist)
print(max)
posted @ 2021-12-29 13:48  keep2021  阅读(198)  评论(0)    收藏  举报