53. 最大子数组和 + 最大子数组
给你一个整数数组 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:
思路地址
代码1:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
n = len(nums)
dp = [0] * n
dp[0] = nums[0]
for i in range(1, n):
if dp[i-1] >= 0:
dp[i] = dp[i-1] + nums[i]
else:
dp[i] = nums[i]
return max(dp)
代码2:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
n = len(nums)
maxsum = nums[0]
summ = 0
for i in range(n):
summ = max(summ+nums[i], nums[i]) # 找到max(当前i值,当前i值+前i项最大数组和)
maxsum = max(maxsum, summ) # 更新最大数组和
return maxsum
衍生1:
不仅返回最大数组和,还返回具体数值
代码:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
begin = 0
left, right = 0, 0
summ = 0
maxsum = nums[0]
n = len(nums)
for i in range(n):
if summ >= 0:
summ += nums[i]
else:
summ = nums[i]
begin = i
if maxsum < summ:
maxsum = summ
left = begin
right = i
# print(maxsum, left, right)
return maxsum