zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    chrome手动同步书签
    MySQL(5.6/5.7版本)卸载方法
    Windows 搭建IIS+PHP+MySQL环境
    按照innode删除结点
    wsl区分大小win10不区分大小写解决方案
    Docker容器里的centos疑难杂症
    [UGUI]源码调试和修改
    [UnityAPI]EditorWindow类 & Editor类
    [UnityAPI]Selection类
    [Lua]require
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5628176.html
Copyright © 2011-2022 走看看