53. Maximum Subarray -Easy

来源:互联网 发布:知之深爱之切全文pdf 编辑:程序博客网 时间:2024/06/03 19:21

Question

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

找到一个元素总和最大的连续子数组(包含至少一个数字)

Example

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.

Solution

  • 动态规划解。定义dp[i]:以第i个元素结尾的连续子数组的最大总和。递推式:dp[i] = max(dp[i - 1] + nums[i], nums[i]),即比较它加上前面的最大总和和它本身,取较大者。额外维护一个res记录最大总和即可。

    class Solution(object):    def maxSubArray(self, nums):        """        :type nums: List[int]        :rtype: int        """        if len(nums) == 0: return 0        dp = [0] * len(nums)        dp[0] = nums[0]        res = nums[0]  # 维护最大总和        for index_n in range(1, len(nums)):            dp[index_n] = max(dp[index_n - 1] + nums[index_n], nums[index_n])            res = max(res, dp[index_n])        return res
0 0
原创粉丝点击