Maximum Subarray(最大连续子序列和)

https://leetcode.com/problems/maximum-subarray/

思路:

  1. 如果全为负值,那么取最大值
  2. 如果有非负值,那么我们依次计算到当前位置为止的最大值。假设有n个元素,那么最大连续子序列只可能以0~n-1中某个位置结尾。当我们遍历到第i个元素时,判断以位置i-1为结尾的最大元素子序列和是否小于0,如果小于0,那么以位置i为结尾的最大连续子序列和为位置i对应的元素;否则,以位置i为结尾的最大连续子序列和为(以位置i-1为结尾的最大元素子序列和 + 位置i的元素)

代码

class Solution(object):
    def maxSubArray(self, nums):
        """ 
        :type nums: List[int]
        :rtype: int
        """
        max_sum = nums[0]
        max_sum_here = 0 
        for item in nums:
            if max_sum_here < 0:
                max_sum_here = item
            else:
                max_sum_here += item
            if max_sum_here > max_sum:
                max_sum = max_sum_here
        return max_sum

if __name__ == '__main__':
    s = Solution()
    print(s.maxSubArray([-2,1,-3,4,-1,2,1,-5,4])) 
原文地址:https://www.cnblogs.com/renzongxian/p/5595317.html