#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int loc_start,loc_mid,loc_end;
int a[]={2,2,13,4,7,3,8,12,9,1,5};
int n=sizeof(a)/sizeof(a[0]);
int start=0,mid,end=0;
for(int i=1;i<n;i++)
{
int j=i-1;
int k=i+1;
int sumj=a[i];
int sumk=0;
while(j>=0 && k<=n-1)
{
if(sumj==sumk &&
k-j>end-start)
{
start=j+1;
end=k-1;
mid=i;
break;
}
else if(sumj<sumk)
{
sumj+=a[j];
j--;
}
else
{
sumk+=a[k];
k++;
}
}
}
cout<<"start="<<start<<"
mid= "<<mid<<"end=
"<<end<<"\n";
int s=0;
for(int m=start;m<=mid;m++)
{
cout<<a[m]<<" +
";
s+=a[m];
}
cout<<" =
"<<s<<"\n";
s=0;
for(int l=mid+1;l<=end;l++)
{
cout<<a[l]<<" +
";
s+=a[l];
}
cout<<" = "<<s;
getch();
}
fails for input 2,3,4.....goes to infinite loop
ReplyDeleterahul can you please elaborate on your input array.
ReplyDeletewe are breaking out of the while loop when sumj==sumk else we are incrementing either j or k, so it shouldn't enter the infinite loop.