leetcode53. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

解题思路:O(n)算法,可以证明和为负数的前缀序列不会是最大和序列的前缀,因此当序列和小于0是则中断当前序列。

class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans, sum = -2147483647, 0
        for num in nums:
            sum += num
            ans = max(sum, ans);
            if sum <= 0:
                sum = 0
        return ans


猜你喜欢

转载自blog.csdn.net/empire_03/article/details/80314863