2005-11-14 : 15:18 -Edit- -Reply- -Top- help with concept!!!!!

Updated by philippe on 2005-11-14 15:19

--------------------------------------------------------------------------------

hi,

I am trying to code in C++. Now I am given an array containing both positive and negative integers and am required to find the subarray with the largest sum.

I have written the following code which i feel should work. I would appreciate your comment on this in terms of efficiency, correctness etc.

Please feel free to propose any other methods to carry out the sameCode:int* largest(int* a, int size) { int sum=0,initial=0,final=0,flag=0; int storesum=0,storeinitial=0,storefinal=0; int *subarray; for(int i=0;i <=size;i++) { if(flag==0 && a[i] >0) { initial = i; flag =1; } if(a[i] > 0) sum=sum+a[i]; if(a[i] < 0) { flag = 0; final = i-1; if(storesum < sum) { storesum=sum; storeinitial = initial; storefinal = final; } } } int j=0; for(int i=storeinitial;i<=storefinal;i++) subarray[j++]=a[i]; return(subarray); }

cheers

pf