给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的解法
正常的答案,两端的子序列的和必然大于0.如果最长子序列长度为1就是数组的最大值。
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
start = 0
end = len(nums)-1
maxl = None
while start<=end:
while nums[start]<=0 and start<=end:
maxl = max(maxl,nums[start]) if maxl is not None else nums[start]
start+=1
if start>end:
break
while nums[end]<=0 and end>=start:
maxl = max(maxl,nums[start]) if maxl is not None else nums[end]
end = end-1
if start>end:
break
sumr = 0
while sumr>=0 and end>=start:
sumr+=nums[start]
maxl = max(maxl,sumr) if maxl is not None else sumr
start+=1
if start>end:
break
suml = 0
while suml>0 and end>=start:
suml+=nums[end]
maxl = max(maxl,suml) if maxl is not None else suml
end-=1
if start>end:
break
return maxl
官方题解
class Solution:
def maxSubArray(self, nums: 'List[int]') -> 'int':
n = len(nums)
max_sum = nums[0]
for i in range(1, n):
if nums[i - 1] > 0:
nums[i] += nums[i - 1]
max_sum = max(nums[i], max_sum)
return max_sum