Jun 10, 2009

You're given an array containing both positive and negative integers and required to find the sub-array with the largest sum (O(N) a la KBL). Write a

You're given an array containing both positive and negative integers and required to find the sub-array with the largest sum (O(N) a la KBL). Write a routine in C for the above.
int foo(int* a, int len)
{
int max=0;
int max_t=0;
for(int i=0;i {
if(max_t+a[i]>=0)
max_t=max_t+a[i];
else
{
if(max_t>max)
max=max_t;
max_t=0;
}
}
if(max_t>max) max=max_t;
return max;
}

No comments:

Post a Comment