题目
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
.
标签:Array、Dynamic Programming、Divide and Conquer
相似问题: (E) Best Time to Buy and Sell Stock、(M) Maximum Product Subarray
题意
在给定的数组中找到相加和最大的子串,子串大小最小为1。
解题思路
从头开始累加,如果当前的和为正数则可以继续累加,若为负数,继续相加结果必然较下一个单独数小。又因为必须是连续子串所以要抛弃之前的和,从当前值从新开始。
代码
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m_sum = 0
max_sum = -2147483648
for i in nums:
if m_sum >= 0:
m_sum += i
else:
m_sum = i
if m_sum > max_sum:
max_sum = m_sum
return max_sum