Equaliaze Prices
There are n products in the shop. The price of the i-th product is ai. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.In fact, the owner of the shop can change the price of some product ii in such a way that the difference between the old price of this product ai and the new price bi is at most k. In other words, the condition |ai−bi|≤k should be satisfied (|x| is the absolute value of x).He can change the price for each product not more than once. Note that he can leave the old prices for some products. The new price bi of each product i should be positive (i.e. bi>0 should be satisfied for all ii from 11 to n.Your task is to find out the maximum possible equal price B of all products with the restriction that for all products the condition |ai−B|≤k should be satisfied (where ai is the old price of the product and B is the same new price of all products) or report that it is impossible to find such price B.Note that the chosen price B should be integer.You should answer q independent queries.
Input:
The first line of the input contains one integer q (1≤q≤100) — the number of queries. Each query is presented by two lines.The first line of the query contains two integers n and k (1≤n≤100,1≤k≤1e8) — the number of products and the value k. The second line of the query contains n integers a1, a2,…,an (1≤ai≤1e8), where ai is the price of the i-th product.
Output:
Print q integers, where the i-th integer is the answer B on the i-th query.If it is impossible to equalize prices of all given products with restriction that for all products the condition |ai−B|≤k should be satisfied (where ai is the old price of the product and B is the new equal price of all products), print -1. Otherwise print the maximum possible equal price of all products.
Example Input:
4
5 1
1 1 2 3 1
4 2
6 4 8 5
2 2
1 6
3 5
5 2 5
Output:
2
6
-1
7
我的思路:
此题的要求是找到一个尽可能大的数B(所有产品的新价格),使得
-B|≤k;即B是由每一个加上或者减去一个不大于k的值得到的,而且要保证不管每个
如何变化最后的新价格都要保持一致。则可知B≤(min+k),对于
中最大的价格max,只需要保证(max-k)≤(min+k)就可以保证每一个
都可以变化出B。
#include <iostream>
using namespace std;
int main()
{
int q; //q代表有几组数据
cin >> q;
for(int i=0; i<q; i++)
{//不同组的数据都需要重置n,k和用来存储价格的数组a
int n, k;
int min=1e8+1, max=-1;
int a[105];
cin >> n >> k;
for(int i=0; i<n; i++)
{
cin >> a[i];
}
for(int i=0; i<n; i++)
{
if(a[i]>max)
max = a[i];
if(a[i]<min)
min = a[i];
}
if((min+k)>=(max-k))
{
cout << min+k << endl;
}
else
cout << -1 << endl;
}
}