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
.
思路非常简单,维持两个变量,一个全局最大,一个局部最大
class Solution(object):
    """
     :type nums: List[int]
     :rtype: int
     """
    def maxSubArray(self, nums):
        Max = nums[0]
        F = 0
        for x in nums:
            if F > 0:
                F += x
            else:
                F = x
            if F > Max:
                    Max = F
        return Max
        

你可能感兴趣的:(Maximum Subarray)