Leetcode 53 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.

Kadane算法 - O(n): 如果后面的数值加上当前和小于原数值,则应将当前和丢弃。

class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def maxSubArray(self, nums):
        max_ending_here, max_so_far = nums[0], nums[0]
        for i in range(1,len(nums)):
            max_ending_here = max(nums[i],max_ending_here+nums[i])
            max_so_far = max(max_so_far,max_ending_here)
        return max_so_far

Divide and Conquer - O(nlogn)

...

posted @ 2015-07-03 09:15  lilixu  阅读(112)  评论(0编辑  收藏  举报