Suppose that array A consists of the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4. Then the contiguous subarray with the largest sum is 4, −1, 2, 1, with sum 6.
This problem can be done in O(n) time and O(1) extra space.
Tips: Remember the best sub-array seen so far and the best sub-array ending in i.
def max_subarray(A):
max_so_far = max_ending_here = 0
for x in A:
max_ending_here = max(0, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
#include "stdio.h"
int Max_Sub_Sum(int *a,int b);
int main() { int a[]={8,-2,8,0,-19,8,1,10,-6 }; printf("%d/n",Max_Sub_Sum(a,sizeof(a)/sizeof(*a)));
return 0;
}
int Max_Sub_Sum(int * a,int b)
{
int maxsum=0;
int cursum=0;
int beg;
int end;
for(int i=0,j=0;j<b;j++)
{
cursum+=a[j];
if(cursum>maxsum)
{
maxsum=cursum;
beg=i;
end=j;
}
if(cursum<0)
{
i=j+1;
cursum=0;
}
}
printf("begin: %d/n",beg);
printf("end : %d/n",end);
return maxsum;
}