Maximum Subarray

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.

C++:
01 class Solution {
02 public:
03     int maxSubArray(int A[], int n) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         if(n==0)
07             return 0;
08         int max=A[0];
09         int sum=0;
10         for(int i=0;i<n;i++)
11         {
12             sum+=A[i];
13             max=max>sum?max:sum;
14             sum=sum>=0?sum:0;
15         }
16         return max;
17     }
18 };
Advertisements
This entry was posted in Greedy algorithm. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s