DAY25:leetcode #53 Maximum Subarray

来源:互联网 发布:nba数据查询 编辑:程序博客网 时间:2024/04/29 18:18

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.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Subscribe to see which companies asked this question

class Solution(object):    def maxSubArray(self, nums):        """        :type nums: List[int]        :rtype: int        """        ThisSum = 0        MaxSum = -10000        for i in range(0, len(nums)):            if ThisSum < 0:                ThisSum = 0            ThisSum = ThisSum + nums[i]            MaxSum = max(ThisSum, MaxSum)        return MaxSum        

这道题的难点在于,数组中的大的负数应该怎么处理。比如[1, 2, 3, -100, 2],应该返回6;[1, 2, 3, -100, 20],应该返回20。这个求解思路还是很巧妙的,ThisSum用来指示当前子序列的最大部分和,MaxSum用来指示曾经出现过的子序列最大部分和。

对于ThisSum而言,有一个很巧妙的等价条件:如果当前子序列的ThisSum < 0,那么应该放弃掉这个子序列,把ThisSum设为0,从下一个元素开始继续探测。

这个条件的正确性也是显而易见的,当一个子序列的和<0时,在它的后面加入任何数字,所产生的部分和一定比这个数字单独构成的子序列要小。

另外More practice中提到的分治算法,我没有想明白。难道以上算法就算是分治了么?还需要探究一下。

0 0
原创粉丝点击