LeetCode刷题笔记—最大子序列和

最大子序列和


最大子序列和

原题地址:最大子序列和
题目描述:

给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

子数组 是数组中的一个连续部分。

示例1:

输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。

示例2:

输入:nums = [1]
输出:1

示例3:

输入:nums = [5,4,-1,7,8]
输出:23

思路:

官网上提示使用分治法来解决问题,但单纯从最简洁的代码角度出发,我们考虑动态规划来解决该问题。

对于如图所示的数组,从左到右遍历。
在这里插入图片描述
1.设置两个变量tempMax和finalMax,分别记录暂时的最大值和最终的最大值。

2.每遍历一个数组中的元素array[i],就更新 t e m p M a x = t e m p M a x + a r r a y [ i ] tempMax = tempMax+array[i] tempMax=tempMax+array[i]

3.判断tempMax是否大于array[i],若大于,则往下执行,若小于或等于,等于之前的数组中的元素求和后对当前的最大值为负贡献或无贡献,将其全部扔掉,并令 t e m p M a x = a r r a y [ i ] tempMax=array[i] tempMax=array[i],即从当前的元素重新开始求和。

4.判断tempMax和finalMax的大小关系,若大于,令 f i n a l M a x = t e m p M a x finalMax=tempMax finalMax=tempMax,若小于或等于,则不做任何操作。

示例如下:

对于上述的数组,i=0时,有 t e m p M a x = m a x ( 0 , 5 ) = 5 tempMax=max(0, 5)=5 tempMax=max(0,5)=5 f i n a l M a x = ( 0 , 5 ) = 5 finalMax=(0, 5)=5 finalMax=(0,5)=5
在这里插入图片描述
i=1时,有 t e m p M a x = m a x ( 5 − 2 , − 2 ) = 3 tempMax=max(5-2, -2)=3 tempMax=max(52,2)=3 f i n a l M a x = m a x ( 5 , 3 ) = 5 finalMax=max(5, 3)=5 finalMax=max(5,3)=5
在这里插入图片描述
i=2时,有 t e m p M a x = m a x ( 3 − 4 , − 4 ) = − 1 tempMax=max(3-4, -4)=-1 tempMax=max(34,4)=1 f i n a l M a x = m a x ( 5 , − 1 ) = 5 finalMax=max(5, -1)=5 finalMax=max(5,1)=5
在这里插入图片描述
i=3时,有 t e m p M a x = m a x ( − 1 + 3 , 3 ) = 3 tempMax=max(-1+3, 3)=3 tempMax=max(1+3,3)=3 f i n a l M a x = m a x ( 5 , 3 ) = 5 finalMax=max(5, 3)=5 finalMax=max(5,3)=5
在这里插入图片描述
i=4时,有 t e m p M a x = m a x ( 3 − 2 , − 2 ) = 1 tempMax=max(3-2, -2)=1 tempMax=max(32,2)=1 f i n a l M a x = m a x ( 5 , 1 ) = 5 finalMax=max(5, 1)=5 finalMax=max(5,1)=5
在这里插入图片描述
i=5时,有 t e m p M a x = m a x ( 1 + 4 , 4 ) = 5 tempMax=max(1+4, 4)=5 tempMax=max(1+4,4)=5 f i n a l M a x = m a x ( 5 , 5 ) = 5 finalMax=max(5, 5)=5 finalMax=max(5,5)=5
在这里插入图片描述
i=6时,有 t e m p M a x = m a x ( 5 + 1 , 1 ) = 6 tempMax=max(5+1, 1)=6 tempMax=max(5+1,1)=6 f i n a l M a x = m a x ( 5 , 6 ) = 6 finalMax=max(5, 6)=6 finalMax=max(5,6)=6

因此,最后结果为6。

代码如下:

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        tempMax, finalMax= -10e4, -10e4
        for i in range(len(nums)):
            tempMax = max(tempMax+nums[i], nums[i])
            finalMax = max(tempMax, finalMax)
        return finalMax

总结

时间复杂度:

复杂度是 O ( n ) O(n) O(n),n为数组长度,因为只遍历了一次。

空间复杂度:

复杂度是 O ( 1 ) O(1) O(1)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值