Maximum Subarray——python

“””
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
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.
“”“

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        #设2个变量用于存储
        Sum = MaxSum = nums[0]
        for i in range(1,len(nums)):
            Sum = max(Sum+nums[i], nums[i])
            #如果Sum+nums[i]比nums[i]还小,就舍弃。令nums[i]为Sum
            MaxSum = max(MaxSum, Sum)
            #2次递归
        return  MaxSum

猜你喜欢

转载自blog.csdn.net/Everywhere_wwx/article/details/80209104
今日推荐