[Leetcode 55] 53 Maximum Subarray

Problem:

 

Analysis:

Naive solution which compute every possible subarray sum and find the maximum need O(n^3), which is unbearable.

A O(n) solutoin can be found based on the fact that. If the current sum is greater than or equal to 0, we keep add new element to it. If the current sum is less than 0, we restart compute the sum by assign the current value to it. And every time, we compare it with the max sum to see if we can update the max sum. This is correct because of the following fact: once the current sum less than 0, it will make negative contribution to the following sum procedure. To find the max, the best way is just to throw away these negative part and start from 0. A more pricese explaination requires DP analysis, which I'm not so good at....

 

Code:

 1 class Solution {
 2 public:
 3     int maxSubArray(int A[], int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int max, cur;
 7         
 8         max = cur = A[0];
 9         for (int i=1; i<n; i++) {
10             if (cur >= 0) {
11                 cur += A[i];
12             } else {
13                 cur = A[i];
14             }
15             
16             if (max < cur)
17                 max = cur;
18         }
19         
20         return max;
21     }
22 };
View Code

 

posted on 2013-05-26 07:26  freeneng  阅读(150)  评论(0编辑  收藏  举报

导航