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
.
class Solution {
public:
int maxSubArray(int A[], int n) {
if(A==NULL)
return 0;
int result=INT_MIN,temp=0;
for(int i=0;i<n;i++)
{
temp+=A[i];
result=max(temp,result);
if(temp<0)
temp=0;
}
return result;
}
};
class Solution {
public:
int maxSubArray(int A[], int n) {
if(A==NULL)
return 0;
maxSub(A, 0, n-1);
}
int maxSub(int A[], int b, int e)
{
if(b==e)
return A[b];
if(b+1==e)
return max(max(A[b],A[e]),A[b]+A[e]);
int mid=(b+e)/2;
int maxLeft=maxSub(A, b, mid-1);
int maxRight=maxSub(A,mid+1,e);
int maxMid;
int maxMidLeft=INT_MIN,maxMidRight=INT_MIN;
int maxTemp1=0,maxTemp2=0;
for(int i=mid;i>=0;i--)
{
maxTemp1+=A[i];
maxMidLeft=max(maxMidLeft,maxTemp1);
}
for(int i=mid;i<=e;i++)
{
maxTemp2+=A[i];
maxMidRight=max(maxMidRight, maxTemp2);
}
maxMid=maxMidRight+maxMidLeft-A[mid];
return max(max(maxLeft,maxMid),maxRight);
}
};