B. Make Them Equal
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
题意:给你N个数,然后你可以对每个数有三种操作,加一个数a,或者减一个数a,或者不变,最后你可以让N个数都变得相等就输出a,否则,就输出-1;
解题思路:首先我们得找出这些数的最大最小值,这是因为三种操作满足的话肯定就是在最大值与最小值的差之间。然后,我们让最小值加上一个数,再判断最大值减去一个数或者不减他们是否相等。当它们相等时,我们就确定了这个值,然后我们需要用确定的这个值对N个数进行这三种操作。
#include<stdio.h>
int main()
{
int n, i, j, ans = 9999999;
scanf("%d", &n);
int a[101];
int min, max, d, noo = 1;
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for (i = 0; i < n; i++)//找出最大,最小值;
{
if (i == 0)
{
min = max = a[i];
}
else
{
if (a[i] < min)
min = a[i];
else if (a[i] > max)max = a[i];
}
}
for (d = 0; d <= max - min; d++)//要找得数存在,肯定在最大值,最小值之差之间;
{
int nod = 0;
int num = min + d;//最小值加一个数,
if (num == max - d || num == max)//最大值减一个数,或者,最大值与它最小值加一个数后的值相等,则执行
{
for (i = 0; i < n; i++)//对每个数进行判断;
{
if (a[i] + d != num && a[i] - d != num && a[i] != num)//进行三种操作都不等于num,则一定不符合;
nod = 1;
}
}
else nod = 1;
if (nod == 0)//当它满足时
{
if (ans >= d)//找出最小得一个符合得数;
{
ans = d;
noo = 0;
}
}
}
if(noo==0)
printf("%d\n", ans);
else
printf("-1\n");
return 0;
}