Here is My Solution for the question below.
But it is wrong.
Can anyone please tell me where is fault in my code.
For which test case it fells.
#include<iostream>
using namespace std;
int main()
{
long long int t; cin>>t;
while(t--)
{
long long int n; cin>>n;
long long int *a,*b,k,d[2],cd,ans ;
a=new long long int[n];
b=new long long 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)
{
long long int count=0;
cd=a[1]-a[0];
if (n==4)
{
if (a[1]+cd==a[2])
{
cout<<a[3]<<endl;
}
else if (a[1]+cd==a[3])
{
cout<<a[2]<<endl;
}
else
{
cout<<-1<<endl;
}
}
else{
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;
}