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.

More practice:If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

01 int maxSubArray(int A[], int n)
02  {
03      if(n==0)
04          return 0;
05      int sum=0;
06      int maxsum=A[0];
07      for(int i=0;i<n;i++){
08          sum+=A[i];
09          if(sum>maxsum)
10              maxsum=sum;
11          if(sum<0)
12              sum=0;
13      }
14      return maxsum;
15 }
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s