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

Maximum Subarray

时间:2014-12-09 17:12:39      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   sp   for   on   div   log   bs   

It‘s obvious an DP problem.

Let‘s define:

$dp[i] := $ the maximum sum of subarray in the first $i$ elements.

 

From the base point, the optimal subarray may contain element $A[i]$ or not.

  1. optimal subarray without $A[i]$, so $dp[i] = dp[i-1]$.
  2. optimal subarray ending with $A[i]$.

There‘re some subtle issues about the second situation. In order to get the second case, we need to know the optimal solution of array ending with $A[i-1]$.

 

So, we have to define another dp table:

$End[i] := $ the maximum sum of subarray ending with $A[i]$.

Obviously, the $End$ array satisfies:

End[i] = max(End[i-1] + A[i], A[i]);

 In fact, we can simplify as

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

 

As both $dp[i]$ and $End[i]$ only relate the previous step, we can use a variable instead of an array to store the result.

end = (end > 0) ? end + A[i] : A[i];
dp = max(dp, end); 

 

Of course, at the initial stage, we consider only one element $A[0]$, thus, we can initialize $dp, end$ as: 

dp = end = A[0];

 


The complete code is:

class Solution {
public:
    int maxSubArray(int A[], int n) {
        int dp = A[0];
        int end = dp;
        
        for(int i = 1; i < n; ++i){
            end = end > 0 ? end + A[i] : A[i];
            dp = dp > end ? dp : end;
        }
        
        return dp;
    }
};

 

Maximum Subarray

标签:blog   io   ar   sp   for   on   div   log   bs   

原文地址:http://www.cnblogs.com/kid551/p/4153428.html

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