Maximum Subarray

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;
    }
};

 

posted @ 2014-12-09 15:43  kid551  阅读(140)  评论(0编辑  收藏  举报