Leetcode 53. Maximum Subarray

Posted 周洋的Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 53. Maximum Subarray相关的知识,希望对你有一定的参考价值。

简单的dp.

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums: return
        if len(nums) == 1: return nums[0]
        dp = [0] * len(nums)
        dp[0] = nums[0]

        for i, v in enumerate(nums[1:]):
            dp[i+1] = max(dp[i] + v, v)
        return max(dp)

其实不用dp这个数组,就维护一个最大值ret就行.

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums: return
        if len(nums) == 1: return nums[0]
        pre_max=ret = nums[0]

        for v in nums[1:]:
            pre_max = max(pre_max + v, v)
            ret = max(ret, pre_max)
        return ret

 

以上是关于Leetcode 53. Maximum Subarray的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 53. Maximum Subarray

leetcode 53. Maximum Subarray

Leetcode 53 Maximum Subarray

41. leetcode 53. Maximum Subarray

Leetcode53 Maximum Subarray

LeetCode练题——53. Maximum Subarray