码迷,mamicode.com
首页 > 其他好文 > 详细

53. Maximum Subarray

时间:2019-05-26 00:30:53      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:object   pre   out   coding   ini   pytho   最大   odi   app   

53. Maximum Subarray

1 题目

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.

2 解题 && 思路

本题可以使用动态规划的方式来解决。设dp[i]是数组第i处的最大值,则dp[i]的递推表达式是:

  1. 如果dp[i-1]>0,则dp[i] = dp[i-1] + nums[i]
  2. 如果dp[i] < 0 ,则dp[i] = nums[i]

3. 实现

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l = len(nums)
        dp = [None] * l
        dp[0] = nums[0]
        ret = nums[0]
        for i in range(1,l):
            if dp[i-1] >0 :
                dp[i] = dp[i-1] + nums[i]
            else:
                dp[i] = nums[i]
            ret = max(dp[i],ret)
        return ret

53. Maximum Subarray

标签:object   pre   out   coding   ini   pytho   最大   odi   app   

原文地址:https://www.cnblogs.com/bush2582/p/10924449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!