Regarding my solution of the lost arithemetic aequence

Can anyone please tell me where is the fault.
here is my solution

#include<iostream>
using namespace std;
int main()
{
int t; cin>>t;
 while(t--)
  {
   int n; cin>>n;
   int *a,*b,k,d[2],cd,ans ;
   a=new int[n];
   b=new int[n-1];
   d[0]=0;  d[1]=0;
   for (int i=0;i<n;i++)
   {cin>>a[i];}
   if (n==2)
   {
       if (a[0]<a[1])
        cout<<a[0]<<endl;
       else
        cout<<a[1]<<endl;
   }
   else if (n==3)
   {
       if (a[0]<a[1])
        ans=a[0] ;
        else
        ans=a[1];
        if (ans<a[2])
            cout<<ans<<endl;
        else
            cout<<a[2]<<endl;
   }
   else {
   b[0]=a[0] ;
   for (int j=1;j<=2;j++)
   {
     for (int i=2;i<n;i++)

     {
       b[i-j]=a[i-j+1];
     }
     for (int k=0;k<n-3;k++)
     {
         if (2*b[k+1]!=b[k]+b[k+2])
         break;
         else if (k==n-4)
         d[j-1]=b[1]-b[0] ;
     }
   }
   if (d[0]==0 && d[1]==0)
   {
       int count=0;
       cd=a[1]-a[0];
       for (int i=2;i<n;i++)
       {
           if (a[i]!=a[i-1]+cd)
            {count++; ans=a[i-1];}
       }
       if (count==2)
        cout<<ans<<endl;
       else
       cout<<-1<<endl;

   }
   else if (d[0]==0 && d[1]!=0)
   {
       if (n==4)
       {
           if(2*a[1]==a[0]+a[3])
           {
                if (a[2]<a[0])
                cout<<a[2]<<endl;
                else
                cout<<a[0]<<endl;
           }
           if (2*a[1]==a[0]+a[2])
           {
               if (a[3]<a[0])
                cout<<a[3]<<endl;
               else
                cout<<a[0]<<endl;
           }
       }
       else
       {
           cout<<a[0]<<endl;
       }
   }
   else if (d[0]!=0 && d[1]==0)
   {

       if (n==4)
       {
           if(2*a[1]==a[0]+a[3])
           {
                if (a[2]<a[0])
                cout<<a[2]<<endl;
                else
                cout<<a[1]<<endl;
           }
           if (2*a[1]==a[0]+a[2])
           {
               if (a[3]<a[1])
                cout<<a[3]<<endl;
               else
                cout<<a[1]<<endl;
           }
       }
       else
       {
           cout<<a[1]<<endl;
       }
   }
   else
   {
       if (d[0]==d[1])
       {
           if (a[0]<a[n-1])
            cout<<a[0]<<endl;
           else
            cout<<a[n-1]<<endl;
       }
       else
       {
           if (a[0]<a[1])
            cout<<a[0]<<endl;
           else
            cout<<a[1]<<endl;
       }
   }

   }
  }
return 0;
}

Your code fails on the sample test case itself-

Input
1
4
1 5 3 4
Your Output
3
Correct Output
-1

Also, please post problem link instead of problem name. It will help people get to problem statement faster.

//