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

【LeetCode】Maximum Subarray

时间:2015-03-12 22:42:13      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:leetcode

    题意:

    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.


     思路:

     很直接的最长上升子序列,线性 dp, dp 式子为:

     dp[i] = dp[i-1] > 0?(A[i] + dp[i-1]):A[i]

     然后迭代更新最大值就好。(会不会觉得 python 的实现写得很不一样?)


     代码:

     C++:

class Solution {
public:
    int maxSubArray(int A[], int n) {
        int ans = A[0];
        int *dp = new int[n];
        dp[0] = A[0];

        for(int i = 1;i < n;++i)
        {
            dp[i] = dp[i-1]>0?(A[i] + dp[i-1]):A[i];
            if(dp[i] > ans)
                ans = dp[i];
        }

        return ans;
    }
};

      Python:

class Solution:
    # @param A, a list of integers
    # @return an integer
    def maxSubArray(self, A):
        ans = A[0]
        n = len(A)
        for i in range(1,n):
            if A[i-1] > 0:
                A[i] = A[i-1] + A[i]
                
            if A[i] > ans:
                ans = A[i]
        return ans

【LeetCode】Maximum Subarray

标签:leetcode

原文地址:http://blog.csdn.net/jcjc918/article/details/43900427

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