最大子序列和
原题地址:最大子序列和
题目描述:
给你一个整数数组 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(5−2,−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(3−4,−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(3−2,−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)。