leetcode-53 最大子序和
题目描述:
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
注:使用python3提交,会出ujson的错误,使用python2提交即可,应该是系统问题
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if not nums:
return
sumc = [0]*(len(nums))
sumc[0] = nums[0]
for i in range(1,len(nums)):
sumc[i] = max(sumc[i-1]+nums[i],nums[i])
max_sum = max(sumc)
# index = sum_.index(sum_)
# res = [nums[index]]
# index -= 1
# while index>=0 and (max_sum-sum_[index+1]==nums[index]):
# res.append(nums[index])
# index -= 1
return max_sum
如果需要输出相应的子数组
从最大值索引到之前所有和大于0的位置都是
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return
sumc = [0]*(len(nums))
sumc[0] = nums[0]
for i in range(1,len(nums)):
sumc[i] = max(sumc[i-1]+nums[i],nums[i])
max_sum = max_res= max(sumc)
index = sumc.index(max_sum)
res = [nums[index]]
index -= 1
while index>=0 and (sumc[index]>=0):
res.append(nums[index])
index -= 1
print(res[::-1])
return max_res