an array contain +ve and -ve element, find subarray whose sum =0;

an array contain +ve and -ve element, find subarray whose sum =0;

Lets take input array as a[]={-3,2,4,-6,-8,10,11}

Comments

  1. for(i=0;i<7;i++)
    {
    for(j=0;j<=i;j++)
    {
    sum[j]=sum[j]+a[i];
    if(sum[j]==0)
    {
    flag=1;
    break;
    }
    }
    if(flag==1)
    break;
    }

    printf("The subarray is from %d to %d",j,i);

    ReplyDelete
  2. this solution has o(n^2) running time,try to optimize it.

    ReplyDelete
  3. you can create a temp array storing consecutive sum of elements.
    temp[]={-3,-1,3,-3,-11,-1,10}
    insert elements in hash if collision occurs then elements between these two indices sum zero.

    ReplyDelete

Post a Comment

Popular posts from this blog