题目:最大子序和
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn3cg3/
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
例1
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
例2
输入:nums = [1]
输出:1
例3
输入:nums = [0]
输出:0
例4
输入:nums = [-1]
输出:-1
思路:
1、定义dp[i]表示当前数组前i位中的某一位到i位的最大连续子数组和
2、计算i+1个元素构成的数组最大子数组和,既计算dp[i],只需判断dp[i-1]是大于0还是小于0,大于0的话就继续累加。
3、确定边界值,dp[0] = nums[0]
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0 for _ in range(len(nums))]
dp[0] = nums[0]
max_num = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i-1], 0) + nums[i]
max_num = max(max_num, dp[i])
return max_num
题目改进:获取最大子序和的子数组
思路:如果需要获取最大子序和的子数组的话,则只要提取dp列表中最大的dp[i]到前i个不为负的数的下标,则下标对应nums下标的数就是最大子序数组。
具体实现代码如下
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0 for _ in range(len(nums))]
dp[0] = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i - 1], 0) + nums[i]
maxindex = dp.index(max(dp))
minindex = 0
for j in range(maxindex-1, -1, -1):
if dp[j] < 0:
minindex = j + 1
break
if maxindex == minindex:
return nums[maxindex:maxindex+1]
else:
return nums[minindex:maxindex+1]