首页 > 其他 > 详细

Maximum Subarray

时间:2016-06-29 21:52:55      阅读:235      评论:0      收藏: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.

这个一道非常经典的题目,剑指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

 

Maximum Subarray

原文:http://www.cnblogs.com/sherylwang/p/5628176.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!