leetcode24_leetcode(24)-最大子序列和

给定一个整数数组 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值