美文网首页
53.Maximum Subarray

53.Maximum Subarray

作者: l_b_n | 来源:发表于2017-08-22 09:25 被阅读0次

题目介绍

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.

代码(python)

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        size = len(nums)
        d,sums=0,nums[0]
        for i in range(size):
            if d > 0:
                d += nums[I]
            else:
                d = nums[I]
            if d > sums:
                sums = d
    return sums
      

分析

这是一个很简单的动态规划的问题,我们在一个数组的上面不断的累积d的值,只要d的值大于0那么它与后面的值相加就会可能增大,d的累积值不断的保存起来,与已经保存的值比较,当d的值最后<=0了我们就把当前的nums[i]保存起来,重新开始。

相关文章

网友评论

      本文标题:53.Maximum Subarray

      本文链接:https://www.haomeiwen.com/subject/brukdxtx.html