You are given a sequence a1,a2,…,an consisting of n integers.
You can choose any non-negative integer D (i.e. D≥0), and for each ai you can:
add D (only once), i. e. perform ai:=ai+D, or
subtract D (only once), i. e. perform ai:=ai−D, or
leave the value of ai unchanged.
It is possible that after an operation the value ai becomes negative.
Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all ai are equal (i.e. a1=a2=⋯=an).
Print the required D or, if it is impossible to choose such value D, print -1.
For example, for array [2,8] the value D=3 is minimum possible because you can obtain the array [5,5] if you will add D to 2 and subtract D from 8. And for array [1,4,7,7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4,4,4,4].
Input
The first line of the input contains one integer n (1≤n≤100) — the number of elements in a.
The second line of the input contains n integers a1,a2,…,an (1≤ai≤100) — the sequence a.
Output
Print one integer — the minimum non-negative integer value D such that if you add this value to some ai, subtract this value from some ai and leave some ai without changes, all obtained values become equal.
If it is impossible to choose such value D, print -1.
Examples
input
6
1 4 4 7 4 1
output
3
input
5
2 2 5 2 5
output
3
input
4
1 3 3 7
output
1
input
2
2 8
output
3
思路:
原本读完这道题我想到的思路是将每个数都加起来(重复的不加)然后除以一共加几个数的个数,但是,并不对,因为只有三个数以下及三个数可以有这样一个数,其他的都不存在,因为四个不同的数,加起来到,最后,你会发现即使这个和可以被四整除,但也做不到所有数加或减一个数等于它,五个数也一样。
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<iomanip>
#include<cstring>
#include<string>
#include<cmath>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define ll long long
#define mes(x,y) memset(x,y,sizeof(x))
#define maxn 2147483648+30
using namespace std;
int main(){
long n;
cin>>n;
long a,z,b[200];mes(b,0);
map<long,long>mmap;mmap.clear();
long sum=0,total=0;
for(int i=0;i<n;i++){
cin>>a;
if(mmap[a]==0){
b[total++]=a;mmap[a]=1;
}
}
sort(b,b+total);
if(total==1)cout<<"0"<<endl;
else if(total==2){
sum=b[1]+b[0];
if(sum%2==0){
sum/=2;
if((b[1]-sum)>b[1]-b[0])sum=b[1]-b[0];
cout<<b[1]-sum<<endl;
}
else{
cout<<b[1]-b[0]<<endl;
}
}
else if(total==3){
if(b[1]*2==b[0]+b[2]){
cout<<b[1]-b[0]<<endl;
}
else {
cout<<"-1"<<endl;
}
}
else cout<<"-1"<<endl;
return 0;
}