题目内容
https://leetcode-cn.com/problems/maximum-subarray/
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
给定一个整数数组 nums
,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
题目思路
这道题可以使用动态规划的方法。创建一个动态规划数字dp,dp[i]表示已第i个数字为序列最后一个的数字的序列最大值。那么对于每一个dpi,则可能有两种情况。第一种是它自己,第二种是前边的加上它自己。两者选最大的那个就可以。选出最大的那个即可。
程序代码
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#使用动态规划,构建动态规划序列dp[i],表示已i为结尾的序列的最大值
if not nums:
return 0
if len(nums)==1:
return nums[0]
l=len(nums)
dp=[min(nums)]*l
dp[0]=nums[0]
for i in range(1,l):
dp[i]=max(nums[i],nums[i]+dp[i-1])
return max(dp)