Wednesday 1 August 2012

Given an array (length n), we need to find the subarray (length k) such that the sum of the first j elements of the subarray equals the sum of the remaining (k-j) elements of the subarray


#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();
}

2 comments:

  1. fails for input 2,3,4.....goes to infinite loop

    ReplyDelete
  2. rahul can you please elaborate on your input array.
    we 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.

    ReplyDelete