53. 最大子序和
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.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Python代码实现:
先将数组中第一个数存在maxSum中,然后将数组中元素依次相加得sum,每次都和maxSum比较,如果比maxSum大,则替换之并更新maxSum,如果没有maxSum大则继续加下一个,直到再次出现比maxSum大的sum,替换之;一直不出现最后就返回之前记录的maxSum;若中途出现sum小于0,则放弃之前所加之数,重新开始计算。
class Solution:
def maxSubArray(self, nums):
maxSum = nums[0]
sum = 0
for i in range(0,len(nums)):
sum += nums[i]
if sum > maxSum:
maxSum = sum
if sum < 0:
sum = 0
return maxSum