Maximum Subarray

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.

这个一道非常经典的题目,剑指offer上也有。

用DP做思路是最优的,但是DP的做法本身有很多种解释。一种是用f[i]表示以第i 个元素结尾的子数组的最大和。最后的最大和为max(f[i])。

另外一种解释是使用local, global的解法,即我们的f[i]是local, maxsum为global.

其实是用后一种解释更加合理,两种解释的代码也很相同,代码如下:

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        res = [0] * (len(nums)+1)
        maxsum = -sys.maxint-1
        for i in xrange(1, len(nums)+1):
            if res[i-1] <= 0:
                res[i] = nums[i-1]
            else:
                res[i] = res[i-1] + nums[i-1]
            maxsum = max(maxsum, res[i])
        return maxsum

另外一种解释是:

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        Local = nums[0]
        Global= nums[0] 
        for i in xrange(1, len(nums)):
            Local = max(Local + nums[i], nums[i])
            Global = max(Local, Global)
        return Global

 

转载于:https://www.cnblogs.com/sherylwang/p/5628176.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值