Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

The Lost Arithmetic Sequences CodeChef Solution

Problem -The Lost Arithmetic Sequences CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

The Lost Arithmetic Sequences CodeChef Solution in C++17

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
 
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;

typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef pair<ld,ld> pd;

typedef vector<int> vi;
typedef vector<ll> vll;

#define all(v)       v.begin(),v.end()
#define sz(x)        (int)(x).size()
#define alr(v)       v.rbegin(),v.rend()
#define pb           push_back
#define S            second
#define F            first
#define pow2(x)      (1<<(x))
#define sp(x)        cout<<fixed<<setprecision(6)<<x
#define output(x)    cout<<(x?"YES\n":"NO\n")
#define bp(x)        __builtin_popcount(x)
//#define int long long
template<class T> using ordered_set = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
// order_of_key (k) : Number of items strictly smaller than k .
// find_by_order(k) : K-th element in a set (counting from zero).

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

const int inf=2e9;
const int N=2e3+1;
const char nl='\n';
const ll mod=1e9+7;
const ll Binf=1e18;
const ll mod1=998244353;


   
void solve101(){
    int n;cin>>n;
    vector<int> v(n);
    map<int,int> mp;
    for(int i=0;i<n;i++){
        cin>>v[i];
        if(i!=0)
            mp[v[i]-v[i-1]]++;
    }
    debug(mp);
    if(n<=3 || sz(mp)==1){
        cout<<*min_element(all(v))<<nl;
        return;
    }
    vector<int> ans;
    for(int i=0;i<n;i++){
        if(i==0){
            if(mp[v[2]-v[1]]==n-2)
                ans.pb(v[0]);
        }
        else if(i==n-1){
            if(mp[v[n-2]-v[n-3]]==n-2)
                ans.pb(v[n-1]);
        }
        else{
            debug(i,v[i+1]-v[i-1]);
            int a=v[i]-v[i-1],b=v[i+1]-v[i];
            // mp[a]--;mp[b]--;
            if(mp[v[i+1]-v[i-1]]+1==n-2){
                ans.pb(v[i]);
            }
            // mp[a]++,mp[b]++;
        }
    }
    if(sz(ans)==0){
        ans.pb(-1);
    }
    cout<<*min_element(all(ans))<<nl;

}
signed main() {

    ios::sync_with_stdio(0);
    cin.tie(0); 
    cout.tie(0);
    
    int t=1;
    // debug(pr);
    cin>>t; 
    for(int i=1;i<=t;i++){
        // cout<<"Case #"<<i<<": ";
        solve101();  
    }
    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
    return 0;
}
// always check for binary search >.<

// #ifndef ONLINE_JUDGE
//     if (fopen("input.txt", "r"))
//     {
//         freopen("input.txt", "r", stdin);
//         freopen("output.txt", "w", stdout);
//     }
// #endif

The Lost Arithmetic Sequences CodeChef Solution in C++14

#include <bits/stdc++.h>
using namespace std;
#define int               long long
#define pb                push_back
#define ppb               pop_back
#define pf                push_front
#define ppf               pop_front
#define all(x)            (x).begin(),(x).end()
#define uniq(v)           (v).erase(unique(all(v)),(v).end())
#define sz(x)             (int)((x).size())
#define fr                first
#define sc                second
#define pii               pair<int,int>
#define rep(i,a,b)        for(int i=a;i<b;i++)
#define mem1(a)           memset(a,-1,sizeof(a))
#define mem0(a)           memset(a,0,sizeof(a))
#define ppc               __builtin_popcount
#define ppcll             __builtin_popcountll
#define debug(x)  cout<<(x)<<'\n';


template<typename T1,typename T2>istream& operator>>(istream& in,pair<T1,T2> &a){in>>a.fr>>a.sc;return in;}
template<typename T1,typename T2>ostream& operator<<(ostream& out,pair<T1,T2> a){out<<a.fr<<" "<<a.sc;return out;}
template<typename T,typename T1>T amax(T &a,T1 b){if(b>a)a=b;return a;}
template<typename T,typename T1>T amin(T &a,T1 b){if(b<a)a=b;return a;}

const long long INF=1e18;
const int32_t M=1e9+7;
const int32_t MM=998244353;

const int N=0;



void solve(){
    

int n;
cin>>n;
int a[n];
rep(i,0,n)
cin>>a[i];

if(n==2)
{
    cout<<min(a[0],a[1])<<'\n';
    return;
}

map<int,int> m;
for(int i=1;i<n;i++)
{
    m[a[i]-a[i-1]]++;

}
int ans=INF;
for(int i=0;i<n;i++)
{

if(i==0)
{

if(a[1]-a[0]!=a[2]-a[1])
{
    if(m[a[2]-a[1]]==n-2)
        ans=min(ans,a[0]);
}
else 
{

  if(m[a[2]-a[1]]==n-1)
  {
    ans=min(ans,a[0]);
  }

}

}
else if(i<n-1)
{
int p=a[i]-a[i-1];
int q=a[i+1]-a[i];
int r=a[i+1]-a[i-1];
int add=0;
if(p==r) add++;
if(q==r) add++;

if(m[a[i+1]-a[i-1]]+1-add==n-2 )
{
    ans=min(ans,a[i]);
}



}
else 
{


if(m[a[1]-a[0]]==n-2 && a[i]-a[i-1]!=a[1]-a[0])
{
ans=min(ans,a[i]);
}
else if(m[a[1]-a[0]]-1==n-2 && a[i]-a[i-1]==a[1]-a[0])
{
    ans=min(ans,a[i]);
}


}

}
if(ans==INF) ans=-1;

cout<<ans<<'\n';
    
}
signed main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    #ifdef SIEVE
        sieve();
    #endif
    #ifdef NCR
        init();
    #endif
    int t=1;
    cin>>t;
    while(t--) solve();
    return 0;
}

The Lost Arithmetic Sequences CodeChef Solution in PYTH 3

# cook your dish here
for _ in range(int(input())):
    n=int(input())
    a=[int(i) for i in input().split()]
    f=[0]*n
    g=[0]*n
    if n<=3:
        print(min(a))
    else:
        f[0]=f[1]=f[2]=1 
        for i in range(2,n):
            f[i]=(a[i]-a[i-1]==a[i-1]-a[i-2] and f[i-1])

        g[n-1]=g[n-2]=1 
        for i in range(n-3,-1,-1):
            g[i]=(a[i+1]-a[i]==a[i+2]-a[i+1] and g[i+1])

        res=10**10 
        if g[1]:
            res=min(res,a[0])
        if g[2]:
            if a[2]-a[0]==a[3]-a[2]:
                res=min(res,a[1])
        if f[n-2]:
            res=min(res,a[n-1])
        if f[n-3]:
            if a[n-3]-a[n-1]==a[n-4]-a[n-3]:
                res=min(res,a[n-2])
                
        for i in range(2,n-2,1):
            if f[i-1] and g[i+1] and a[i+1]-a[i-1]==a[i+2]-a[i+1]==a[i-1]-a[i-2]:
                res=min(res,a[i])
        if res==10**10:
            print(-1)
        else:
            print(res)
            

The Lost Arithmetic Sequences CodeChef Solution in C

#include<stdio.h>
int main()
{
int t;
scanf("%d",&t);     

while(t--)
{
    int n,i;
    scanf("%d",&n);     
     int a[n];

    for(i=0;i<n;i++)
        scanf("%d",&a[i]); 

    if(n==2)
    {

        if(a[0]>a[1])
            a[0]=a[1];
        printf("%d\n",a[0]);
        continue;
    }

    int c=0;
     int s=-1;
    int min=-1;
     int d=a[1]-a[0];

    for(i=2;i<n;i++)
    {
        if(a[i]!=(a[0]+(i-c)*d))     
        {
            c++;
            min=a[i];

        }
        if(c==2)
        {
            min=-1;
            break;
        }
    }

    if(c==0&&d<0)       
    {
        s=a[n-1];
        printf("%d\n",s);
        continue;
    }
    
    if(c==0)        
    {
        s=a[0];
        printf("%d\n",s);
        continue;
    }

    if(c==1)
    {
          s=min;
    }

    c=1;
    min=a[1];
    d=a[2]-a[0];

    for(i=3;i<n;i++)
    {
        if(a[i]!=(a[i-1]+d))
        {
            c++;
            break;
        }
    }
    if(c==1)
    {
        if(s==-1)
            s=min;
        else
            if(min<s)
                s=min;
    }

    c=1;
    min=a[0];
    d=a[2]-a[1];

    for(i=3;i<n;i++)
    {
        if(a[i]!=(a[i-1]+d))
        {
            c++;
            break;
        }
    }

    if(c==1)
    {
        if(s==-1)
            s=min;
        else
            if(min<s)
                s=min;
    }

    printf("%d\n",s);
}
return 0;
}

The Lost Arithmetic Sequences CodeChef Solution in JAVA

/* package codechef; // don't place package name! */
import java.util.*;


import java.lang.*;
//import java.math.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
 class CodeChef
{
 public static class FastReader {

		BufferedReader b;
		StringTokenizer s;
		public FastReader() {
			b=new BufferedReader(new InputStreamReader(System.in));
		}
		String next() {
			while(s==null ||!s.hasMoreElements()) {
				try {
					s=new StringTokenizer(b.readLine());
				}
				catch(IOException e) {
					e.printStackTrace();
				}
			}
			return s.nextToken();
		}
		public int nextInt() {
			return Integer.parseInt(next());
		}
		public long nextLong() {
			return Long.parseLong(next());
		}
		public double nextDouble() {
			return Double.parseDouble(next());
		}
		String nextLine() {
			String str="";
			try {
				str=b.readLine();
			}
			catch(IOException e) {
				e.printStackTrace();
			}
			return str;
		}
		boolean hasNext() {
		    if (s != null && s.hasMoreTokens()) {
		        return true;
		    }
		    String tmp;
		    try {
		        b.mark(1000);
		        tmp = b.readLine();
		        if (tmp == null) {
		            return false;
		        }
		        b.reset();
		    } catch (IOException e) {
		        return false;
		    }
		    return true;
		}
	
}
public static int md=(int)(1e9+7);
public static HashMap<Long,HashMap<Integer,Long>> hm;
public static  ArrayList<trip> ans;
public static boolean fg;
public static int dp[][];
public static int anss;
static final int MAXN = 1000001;
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
	FastReader sc=new FastReader();
	BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
	if(sc.hasNext()){
		  int t=sc.nextInt();
		  while(t--!=0) {
			  int n=sc.nextInt();
			  int a[]=new int[n];
			  HashMap<Integer,Integer> hm=new HashMap<>();
			  for(int i=0;i<n;i++)a[i]=sc.nextInt();
			  if(n<=3) {
				  int mn=Integer.MAX_VALUE;
				  for(int i=0;i<n;i++)mn=Math.min(mn, a[i]);
				  log.write(mn+"\n");
			  }
			  else {
			  int maj=-1,mx=-1;
			  for(int i=1;i<n;i++) {
				  int diff=a[i]-a[i-1];
				  hm.put(diff, hm.getOrDefault(diff, 0)+1);
				  if(mx<hm.get(diff)) {
					  mx=hm.get(diff);
					  maj=diff;
				  }
			  }
			      if(mx==n-1) {
			    	  if(maj>=0)log.write(a[0]+"\n");
			    	  else log.write(a[n-1]+"\n");
			      }
			      else {
			      int cnt[]=new int[n];
				  for(int i=1;i<n;i++) {
					 int diff=a[i]-a[i-1];
					 if(diff!=maj) {
						 cnt[i]++;
						 cnt[i-1]++;
					 }
				  }
				  boolean fg=true;
				  int ind=-1;
				  for(int i=0;i<n;i++) {
					  if(cnt[i]==2) {
						  ind=i;
						  break;
					  }
				  }
				  if(ind==-1) {
					  if(cnt[0]>=1)ind=0;
					  else ind=n-1;
				  }
				  int cd=Integer.MIN_VALUE;
				  for(int i=1;i<n;i++) {
					  int diff=a[i]-a[i-1];
					  if(i-1==ind) {
						  if(i-2>=0)diff=a[i]-a[i-2];
						  else continue;
					  }
					  else if(i==ind)continue;
					  if(cd==Integer.MIN_VALUE) {
						  cd=diff;
					  }
					  else if(cd!=diff) {
						  fg=false;
						  break;
					  }
				  }
				  if(fg)log.write(a[ind]+"\n");
				  else log.write("-1\n");
			      }
			  }
			     
         }
			   
		  }
		  log.flush(); 
					     	
}	
static String substring(String s,int i,int j) {
	char tp[]=new char[j-i];
	int ptr=0;
	for(int k=i;k<j;k++) {
		tp[ptr++]=s.charAt(k);
	}
	return String.valueOf(tp);
}	
	static boolean manacher_odd(String q) {
	    int n = q.length();
	    q = "$" + q + "^";
char s[]=q.toCharArray();
int p[]=new int[n+2];
int l = 1, r = 1;
for(int i = 1; i <= n; i++) {
    p[i] = Math.max(0, Math.min(r - i, p[l + (r - i)]));
    while(s[i - p[i]] == s[i + p[i]]) {
    	
        if(i-p[i]!=i+p[i])return false;
        p[i]++;
    }
    if(i + p[i] > r) {
        l = i - p[i];
        r = i + p[i];
    }
}
return true;
			}
			
			static void update(int f[],int upd,int ind) {
				int vl=ind;
				while(vl<f.length) {
					f[vl]^=upd;
					int tp=~vl;
					tp++;
					tp&=vl;
					vl+=tp;
				}
			}	
			static int ser(int f[],int ind) {
				int vl=ind;
				int sm=0;
				while(vl!=0) {
					sm^=f[vl];
					int tp=~vl;
					tp++;
					tp&=vl;
					vl-=tp;
				}
				return sm;
			}	
		public static class pair{
			int a,b;
			public pair(int a,int b) {
				this.a=a;
				this.b=b;
			}
		}
			public static class trip{
				int a,b;
				int c;
				public trip(int a,int b,int c) {
					this.a=a;
					this.b=b;
					this.c=c;
				}
				public int compareTo(trip q) {
					return  this.b-q.b;
				}
			}
			
			
		public static int mm=1000000007;
		static long mul(long a,long b) {
			return ((a%md)*(b%md))%md;
		}	
		static long add(long a,long b) {
			return ((a%md)+(b%md))%md;
		}
		
		static int fact(int n) {
			for(int i=2;i*i<=n;i++) {
				if(n%i==0)return i;
			}
			return 1;
		}
			public static <E> void p(E[][] a,String s) {
				   System.out.println(s);
				   for(int i=0;i<a.length;i++) {
					   for(int j=0;j<a[0].length;j++) {
						   System.out.print(a[i][j]+" ");
			   }
			   
			   System.out.println();
		   }
		  
	}
	
 
//	public static <E> void p(E a,String s){
//		System.out.println(s+"="+a);
//	}
	public static <E> void p(char a[],String s) {
		System.out.print(s+"=");
		for(int i=0;i<a.length;i++)System.out.print(a[i]+" ");
		System.out.println();
	}
	public static <E> void p(ArrayList<E> a,String s){
		System.out.println(s+"="+a);
	}
	public static <E> void p(LinkedList<E> a,String s){
		System.out.println(s+"="+a);
	}
	public static <E> void p(Stack<E> a,String s){
	  System.out.println(s+"="+a);
	}
	public static <E> void p(Queue<E> a,String s){
		System.out.println(s+"="+a);
	}
	
	public static class pairr{
		String a;int b;
		public pairr(String a,int b) {
			this.a=a;
			this.b=b;
		}
	}
	public static class num{
		long v;
	}
static long gcd(long a,long b,num x,num y) {
	if(b==0) {
		x.v=1;
		y.v=0;
		return a;
	}
	num x1=new num();
	num y1=new num();
	long ans=gcd(b,a%b,x1,y1);
	x.v=y1.v;
	y.v=x1.v-(a/b)*y1.v;
	return ans;
}	
static long inverse(long b,long m) {
	num x=new num();
	num y=new num();
	long gc=gcd(b,mm,x,y);
	if(gc!=1) {
		return -1;
	}
	return (x.v%mm+mm)%mm;
	
}
static long div(long a,long b,long m) {
	a%=mm;
	if(inverse(b,mm)==-1)return a/b;
	 return (inverse(b,m)*a)%mm;
}
	
	static long ncr(int n, int r){
	    if(r>n-r)r=n-r;
	    long ans=1;
	    for(int i=0;i<r;i++){
	          ans=(ans%mm*(n-i)%mm)%mm;
	          ans=div(ans,(i+1),mm);
	    }
	    return ans;
	} 		
	static long pow(long a, long pw) {
		long temp;
		if(pw==0)return 1;
		temp=pow(a,pw/2);
		if(pw%2==0)return mul(temp,temp);
		return mul(a,mul(temp,temp));
		
	}	
	static int pow(int a, int pw) {
		int temp;
		if(pw==0)return 1;
		temp=pow(a,pw/2);
		if(pw%2==0)return temp*temp;
		return a*temp*temp;
		
	}	
	public static int m=(int)(1e9+7);
public static int add(int a,int b) {
	return ((a%m)+(b%m))%m;
}
public static int mul(int a,int b) {
	long p=a;
	long q=b;
	long ans=((p%m)*(q%m))%m;
	return (int)(ans);
}
static ArrayList<Long> primeDivisor(long n){
	ArrayList<Long> ar=new ArrayList<>();
	int cnt=0;
	boolean pr=false;
	while(n%2==0) {
		pr=true;
		ar.add(2L);
		n/=2;
		
	}
	for(long i=3;i*i<=n;i+=2) {
		pr=false;
		while(n%i==0) {
			n/=i;
			ar.add(i);
			pr=true;
		}
	
	}
	if(n>2) ar.add(n);
	return ar;
	
}
static ArrayList<Integer> prime(int n){
	boolean vis[]=new boolean[n+1];
	Arrays.fill(vis, true);
	vis[0]=vis[1]=false;
	for(int i=2;i*i<=n;i++) {
		if(vis[i]) {
		for(int j=2*i;j<=n;j+=i) {
			vis[j]=false;
		}
		}
	}
	ArrayList<Integer> ar=new ArrayList<>();
	for(int i=0;i<=n;i++) {
		if(vis[i])ar.add(i);
	}
	return ar;
}
static int gcd(int a,int b) {
	if(b==0)return a;
	return gcd(b,a%b);
}		
static void mergesort(int[] a,int start,int end) {
	if(start>=end)return;
	int mid=start+(end-start)/2;
	mergesort(a,start,mid);
	mergesort(a,mid+1,end);
	merge(a,start,mid,end);
}
static void merge(int []a, int start,int mid,int end) {
	int ptr1=start;
	int ptr2=mid+1;
	int b[]=new int[end-start+1];
	int i=0;
	while(ptr1<=mid && ptr2<=end) {
		if(a[ptr1]<=a[ptr2]) {
			b[i]=a[ptr1];
			ptr1++;
			i++;
		}
		else {
			b[i]=a[ptr2];
			ptr2++;
			i++;
		}
	}
	while(ptr1<=mid) {
		b[i]=a[ptr1];
		ptr1++;
		i++;
	}
	while(ptr2<=end) {
		b[i]=a[ptr2];
		ptr2++;
		i++;
	}
	for(int j=start;j<=end;j++) {
		a[j]=b[j-start];
	}
}

}

					

The Lost Arithmetic Sequences CodeChef Solution in PYPY 3

for _ in range(int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    if n==2:
        print(min(a))
    elif n>=3:
        l=[]
        d1,d2,d3=a[2]-a[0],a[2]-a[1],a[1]-a[0]
        for i in [d1,d3]:
            x,y,count=a[0],1,0
            while y<n:
                if a[y]-x!=i:
                    count+=1
                    res=a[y]
                else:
                    x=a[y]
                y+=1
                if count>=2:
                    break
            if count==1:
                l.append(res)
            elif count==0:
                l.append(min(a[0],a[-1]))
        x,y,count=a[1],2,0
        while y<n:
            if a[y]-x!=d2:
                count+=1
                break
            x=a[y]
            y+=1
        if count==0:
            l.append(a[0])
        if len(l)==0:
            print(-1)
        else:
            print(min(l))

The Lost Arithmetic Sequences CodeChef Solution in PYTH

t = int(input())
def isap(s,d,count,l,e):
    if e == l[0] and count == 1:
        s = s+1
        count  = 0
        for i in range(s,len(l)):
            if l[i] != l[s] + d*(i-s-count):
            
                count = count + 1
            
       
                e = l[i]
                if count == 1:
                
                    return -1
    
        return e
        
    
    else:
        for i in range(s,len(l)):
            if l[i] != l[s] + d*(i-s-count):
            
                count = count + 1
                
       
                e = l[i]
                if count > 1:
                
                    return -1
       
        if count == 1:
            return e
        elif count == 0:
            if d>0:
                return l[0]
            else:
                return l[len(l)-1]
            
    
for i in range(0,t):
    t1 =  int(input())
    l = map(int,raw_input().split())
    if len(l) == 2:
        print l[0]
    elif len(l) == 3:
        m = min(l)
        print m
    elif len(l) >=4:
        x1 = l[1] - l[0]
        x2 = l[2] - l[1]
        x3 = l[3] - l[2]
        y1 = l[2] - l[0]
        y2 = l[3] - l[1]
        if x1 == x2 == x3:

            r = isap(0,x1,0,l,0)
            print r
        elif x1 == y2 and x2 == x3:
         
            r1 = isap(0,x1,0,l,0)
            r2 = isap(0,x2,1,l,l[0])
            if r1 != -1 and r2 != -1:
                if r1>r2:
                    print r2
                else:
                    print r1
            
            elif r1!= -1:
                print r1
            elif r2!= -1:
                print r2
            else:
                print -1
            
                      
        
        elif y1 == x3 and x1 == x2:
        
            r1 = isap(0,y1,0,l,0)
            r2 = isap(0,x1,0,l,0)
            if r1 != -1 and r2 != -1:
                if r1>r2:
                    print r2
                else:
                    print r1
            elif r1!= -1:
                print r1
            elif r2!= -1:
                print r2
            else:
                print -1
        elif x1 == y2:
       
            r = isap(0,x1,0,l,0)
            print r
                
        elif y1 == x3:
         
            r = isap(0,y1,0,l,0)
            print r
        elif x1 == x2:
           

            r = isap(0,x1,0,l,0)
            print r
        elif x2 == x3:
            
            r = isap(0,x2,1,l,l[0])
            print r
        else:
            print -1
            
            
        

The Lost Arithmetic Sequences CodeChef Solution in C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

// (づ°ω°)づミe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    public void Solve()
    {
        for (int tt = ReadInt(); tt > 0; tt--)
        {
            int n = ReadInt();
            var a = ReadIntArray();

            if (n < 4)
            {
                Write(a.Min());
                continue;
            }

            int rd = a[n - 1] - a[n - 2];
            int ld = a[1] - a[0];
            int r = n - 2;
            while (r > 0 && a[r] - a[r - 1] == rd)
                r--;
            int l = 1;
            while (l < n - 1 && a[l + 1] - a[l] == ld)
                l++;

            int ans = int.MaxValue;
            if (r < 2)
                ans = Math.Min(ans, a[0]);
            if (l > n - 3)
                ans = Math.Min(ans, a[n - 1]);
            if (a[2] - a[0] == rd && r < 3)
                ans = Math.Min(ans, a[1]);
            if (a[n - 1] - a[n - 3] == ld && l > n - 4)
                ans = Math.Min(ans, a[n - 2]);
            for (int i = 2; i < n - 2; i++)
                if (ld == rd && a[i + 1] - a[i - 1] == ld)
                    ans = Math.Min(ans, a[i]);
            Write(ans < int.MaxValue ? ans : -1);
        }
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        //reader = new StreamReader(Console.OpenStandardInput());
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("input.txt");
        //writer = new StreamWriter("output.txt");
#endif
        try
        {
            new Solver().Solve();
            //var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
        }
        catch (Exception ex)
        {
#if DEBUG
            Console.WriteLine(ex);
#else
            throw;
#endif
        }
        reader.Close();
        writer.Close();
    }

    #endregion

    #region Read / Write
    private static Queue<string> currentLineTokens = new Queue<string>();
    private static string[] ReadAndSplitLine() { return reader.ReadLine().Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries); }
    public static string ReadToken() { while (currentLineTokens.Count == 0)currentLineTokens = new Queue<string>(ReadAndSplitLine()); return currentLineTokens.Dequeue(); }
    public static int ReadInt() { return int.Parse(ReadToken()); }
    public static long ReadLong() { return long.Parse(ReadToken()); }
    public static double ReadDouble() { return double.Parse(ReadToken(), CultureInfo.InvariantCulture); }
    public static int[] ReadIntArray() { return ReadAndSplitLine().Select(int.Parse).ToArray(); }
    public static long[] ReadLongArray() { return ReadAndSplitLine().Select(long.Parse).ToArray(); }
    public static double[] ReadDoubleArray() { return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); }
    public static int[][] ReadIntMatrix(int numberOfRows) { int[][] matrix = new int[numberOfRows][]; for (int i = 0; i < numberOfRows; i++)matrix[i] = ReadIntArray(); return matrix; }
    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows); int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++) { ret[i] = new int[numberOfRows]; for (int j = 0; j < numberOfRows; j++)ret[i][j] = matrix[j][i]; } return ret;
    }
    public static string[] ReadLines(int quantity) { string[] lines = new string[quantity]; for (int i = 0; i < quantity; i++)lines[i] = reader.ReadLine().Trim(); return lines; }
    public static void WriteArray<T>(IEnumerable<T> array) { writer.WriteLine(string.Join(" ", array)); }
    public static void Write(params object[] array) { WriteArray(array); }
    public static void WriteLines<T>(IEnumerable<T> array) { foreach (var a in array)writer.WriteLine(a); }
    private class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    {
        public new TValue this[TKey key]
        {
            get { return ContainsKey(key) ? base[key] : default(TValue); }
            set { base[key] = value; }
        }
    }
    private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
    #endregion
}
The Lost Arithmetic Sequences CodeChef Solution Review:

In our experience, we suggest you solve this The Lost Arithmetic Sequences CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the The Lost Arithmetic Sequences CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this The Lost Arithmetic Sequences CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *