Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
经常出的题,也属于动态规划。
#把注释去掉可以求得区间。
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s,ms=0,nums[0]
#begin=end=b=e=0
for i in range(len(nums)):
s+=nums[i]
if s>ms:
ms=s
"""
begin=b
e=i
end=e
"""
if s<0:
s=0
"""
b=i+1
e=i+1
"""
#print(nums[begin,end+1])
return ms