给你一个整数数组 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 <= nums.length <=-104 <= nums[i] <=
解法思路
- 状态定义 :用
current_max表示 "以当前元素结尾的最大子数组和"。 - 状态转移 :对于第 i 个元素,有两种选择:
- 仅保留当前元素(前面的子数组和为负,不如重新开始);
- 将当前元素加入前面的子数组(前面的子数组和为正,能增加当前和)。因此状态转移方程为:
current_max = max(nums[i], current_max + nums[i])。
- 全局最大值 :用
global_max记录遍历过程中所有current_max的最大值,即为最终结果。
Python代码:
python
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
# 初始化:当前子数组和、全局最大和均为第一个元素(子数组至少含一个元素)
current_max = global_max = nums[0]
# 遍历数组(从第二个元素开始)
for num in nums[1:]:
# 更新"以当前元素结尾的最大子数组和"
current_max = max(num, current_max + num)
# 更新全局最大和
global_max = max(global_max, current_max)
return global_max
# 测试用例验证
if __name__ == "__main__":
solution = Solution()
# 示例1
print(solution.maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 输出:6
# 示例2
print(solution.maxSubArray([1])) # 输出:1
# 示例3
print(solution.maxSubArray([5, 4, -1, 7, 8])) # 输出:23
LeetCode提交代码:
python
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
from typing import List
# 初始化:当前子数组和、全局最大和均为第一个元素(子数组至少含一个元素)
current_max = global_max = nums[0]
# 遍历数组(从第二个元素开始)
for num in nums[1:]:
# 更新"以当前元素结尾的最大子数组和"
current_max = max(num, current_max + num)
# 更新全局最大和
global_max = max(global_max, current_max)
return global_max
程序运行截图展示:

总结
本文介绍了求解最大子数组和问题的动态规划解法。通过定义current_max表示以当前元素结尾的最大子数组和,状态转移方程为current_max = max(nums[i], current_max + nums[i])。同时维护全局最大值global_max记录最大结果。Python实现中初始化current_max和global_max为第一个元素,遍历数组更新这两个值,最终返回global_max。示例验证了该方法的正确性,时间复杂度为O(n),空间复杂度为O(1)。