41. Maximum Subarray
Description:
给定一个整数数组,找到一个具有最大和的子数组,返回其最大和
《子数组最少包含一个数》
examples:
Input: [−2,2,−3,4,−1,2,1,−5,3]
Output: 6
Explanation: the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Input: [1,2,3,4]
Output: 10
Explanation: the contiguous subarray [1,2,3,4] has the largest sum = 10.
分析:该题为求最大连续子数组的和,思考易得,设置一个flag标记,该flag表示一段区间的数组和,因此我们可令max_num=max(max_num,flag),如果flag小于0.说明之前标记的区间和已经是负数,则加上后面的数字一定小于后面的数字本身和,故此时flag需初始为0,继续遍历。
代码如下:
class Solution:
def maxSubArray(self, nums):
flag, res = 0, nums[0]
for n in nums:
flag += n
res = max(flag, res)
if flag < 0:
flag = 0
return res