#include<stdio.h>
int main(void)
{
    int i,j,n,q;
    scanf("%d",&q);
    long int a,k,min,max;
    for(i=0;i<q;i++)
    {
        scanf("%d %ld",&n,&k);
        for(j=0,max=-1;j<n;j++)
        {
            scanf("%ld",&a);
            if(!j)
                min=a;
            else
                min=min>a?a:min;
            max=max<a?a:max;
        }
        if(max-min>2*k)
            printf("%ld\n",-1);
        else
        {
            if(min==max)
                printf("%ld\n",min+k);
            else if(min+k==max)
                printf("%ld\n",max);
            else if(min+k<max)
                printf("%ld\n",min+k);
            else if(min+k>max)
                printf("%ld\n",min+k);
        }
    }
    return 0;
}


#include <stdio.h>

int main()
{
    int q;

    scanf("%d", &q);

    for(int i=0; i<q; i++){
        int n;
        long long int min, max;
        scanf("%d", &n);
        long long int k, ara[n];
        scanf("%I64d", &k);
        for(int j=0; j<n; j++){
            scanf("%I64d", &ara[j]);
        }
        min = max = ara[0];
        for(int j=0; j<n; j++){
            if(min>ara[j]){
                min = ara[j];
            }
            if(max<ara[j]){
                max = ara[j];
            }
        }
        if((min+k)>=(max-k)){
            printf("%I64d\n", min+k);
        }
        else{
            printf("-1\n");
        }
    }

    return 0;
}


let input = "";
const { EOL } = require("os");
process.stdin.on("data", i => (input += i));

process.stdin.on("end", async () => {
  console.log(func(input));
});

const func = a => {
  let result = "";
  const [q, ...queries] = a.split(EOL);
  for (let i = 0; i < q; i++) {
    const [n, maxPriceDiff] = queries.shift().split(" ").map(a => parseInt(a));
    const products = queries
      .shift()
      .split(" ")
      .map(a => parseInt(a))
      .sort((a, b) => a - b);
    result +=
      (Math.abs(products[products.length - 1] - products[0]) <= maxPriceDiff * 2
        ? products[0] + maxPriceDiff
        : -1) + EOL;
  }
  return result;
};

module.exports = func;


const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  if (c % 2 === 1) {
    [n, k] = d.split(' ').map(Number);
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  let ans = min + k;

  if (min +  k < max - k) {
    ans = - 1;
  }

  console.log(ans);

  c++;
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Trenya260619
{
    class Input
    {
        private static IEnumerator<string> _getinput()
        {
            while (true)
                foreach (string s in Console.ReadLine().Split().Where(x => x.Length > 0))
                    yield return s;
        }

        private IEnumerator<string> input = _getinput();

        public string GetString()
        {
            input.MoveNext();
            return input.Current;
        }

        public int GetInt() { return int.Parse(GetString()); }
        public long GetLong() { return long.Parse(GetString()); }
        public double GetDouble() { return double.Parse(GetString()); }
    }

    class Program
    {
        static Input csin = new Input();

        static void Main(string[] args)
        {
            int q = csin.GetInt();

            for(int qq = 0; qq < q; qq++)
            {
                int n = csin.GetInt();
                long k = csin.GetLong();

                long[] a = new long[n];
                for (int i = 0; i < n; i++) a[i] = csin.GetLong();

                long maxprice = a.Min() + k;
                long minprice = a.Max() - k;

                if (minprice <= maxprice)
                    Console.WriteLine(maxprice);
                else
                    Console.WriteLine(-1);
            }

            //Console.ReadKey();
        }
    }
}


using System;
using System.Linq;

namespace codeforces
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                int[] nk = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
                int[] a = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
                double rez = (a.Max() - a.Min()) / 2.0;
                if (rez > nk[1])
                    Console.WriteLine(-1);
                else Console.WriteLine(a.Min() + nk[1]);
            }
        }
    }
}


using System;
using System.Linq;

namespace codeforces
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                int[] nk = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
                int[] a = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
                double rez = (a.Max() - a.Min()) / 2.0;
                if (rez > nk[1])
                    Console.WriteLine(-1);
                else Console.WriteLine(a.Min() + (int)Math.Ceiling(rez));
            }
        }
    }
}


using System;

using System.IO;

using System.Collections.Generic;

namespace _570

{

    class Program

    {

        static void Main(string[] args)

        {

            solve_570B();

        }

        public static void solve_570B()

        {

            int q = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < q; i++)

            {

                string[] nk = Console.ReadLine().Split(' ');

                int n = Convert.ToInt32(nk[0]);

                int k = Convert.ToInt32(nk[1]);

                string[] a = Console.ReadLine().Split(' ');

                int[] nums = Array.ConvertAll(a, int.Parse);

                //Array.Sort(nums, new Comparison<int>((a1, a2) => a2.CompareTo(a1)));

                Array.Sort(nums);

                int b = nums[0];

                while (Math.Abs(nums[0] - b) <= k)

                {

                    b++;

                }

                if (Math.Abs(nums[nums.Length - 1] - b) >= k)

                {

                    Console.WriteLine(-1);

                }

                else

                {

                    Console.WriteLine("{0}", --b);

                }

            }

        }

        public static void solve_570A()

        {

            string a = Console.ReadLine();

            int sum = 0;

            for (int i = 0; i < a.Length; i++)

            {

                sum += Convert.ToInt32(a[i].ToString());

            }

            int r = Convert.ToInt32(a);

            while (sum % 4 != 0)

            {

                r++;

                sum = 0;

                string s = r.ToString();

                for (int i = 0; i < s.Length; i++)

                {

                    sum += Convert.ToInt32(s[i].ToString());

                }

            }

            Console.Write(r);

        }

    }

}


using System;

using System.IO;

using System.Collections.Generic;

namespace _570

{

    class Program

    {

        static void Main(string[] args)

        {

            solve_570B();

        }

        public static void solve_570B()

        {

            int q = Convert.ToInt32(Console.ReadLine());

            int min = -100;

            for (int i = 0; i < q; i++)

            {

                string[] nk = Console.ReadLine().Split(' ');

                int n = Convert.ToInt32(nk[0]);

                int k = Convert.ToInt32(nk[1]);

                string[] a = Console.ReadLine().Split(' ');

                int[] nums = Array.ConvertAll(a, int.Parse);

                //Array.Sort(nums, new Comparison<int>((a1, a2) => a2.CompareTo(a1)));

                Array.Sort(nums);

                int b = nums[0];

                while (Math.Abs(nums[0] - b) <= k)

                {

                    b++;

                }

                int c = nums[nums.Length - 1];

                while (Math.Abs(nums[nums.Length - 1] - c) <= k)

                {

                    c++;

                }

                --b;

                --c;

                if ((Math.Abs(nums[0] - c) <= k && Math.Abs(nums[nums.Length - 1] - c) <= k) || (Math.Abs(nums[0] - b) <= k && Math.Abs(nums[nums.Length - 1] - b) <= k))

                {

                    Console.WriteLine(Math.Min(b, c));

                }

                else

                {

                    Console.WriteLine(-1);

                }

            }

        }

        public static void solve_570A()

        {

            string a = Console.ReadLine();

            int sum = 0;

            for (int i = 0; i < a.Length; i++)

            {

                sum += Convert.ToInt32(a[i].ToString());

            }

            int r = Convert.ToInt32(a);

            while (sum % 4 != 0)

            {

                r++;

                sum = 0;

                string s = r.ToString();

                for (int i = 0; i < s.Length; i++)

                {

                    sum += Convert.ToInt32(s[i].ToString());

                }

            }

            Console.Write(r);

        }

    }

}


using System;
using System.IO;
using System.Collections.Generic;

namespace cf570
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));
            solve_cf570B();
        }

        public static void solve_cf570B()
        {
            int q = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < q; i++)
            {
                string[] nk = Console.ReadLine().Split(' ');
                int n = Convert.ToInt32(nk[0]);
                int k = Convert.ToInt32(nk[1]);
                string[] a = Console.ReadLine().Split(' ');
                int[] nums = Array.ConvertAll(a, int.Parse);

                int min = int.MaxValue;
                int max = int.MinValue;
                for (int j = 0; j < n; j++)
                {
                    if (min > nums[j])
                    {
                        min = nums[j];
                    }

                    if (max < nums[j])
                    {
                        max = nums[j];
                    }
                }

                int res = Math.Max(min + k, max - k);
                Console.WriteLine(res - min <= k && k >= Math.Abs(res - max) ? res : -1);
            }
        }
    }
}


using System;
using System.Linq;
using CompLib.Util;

public class Program
{

    public void Solve()
    {
        var sc = new Scanner();
        int t = sc.NextInt();
        Console.SetOut(new System.IO.StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        for (int i = 0; i < t; i++)
        {
            Q(sc);
        }
        Console.Out.Flush();
    }

    void Q(Scanner sc)
    {
        int n = sc.NextInt();
        int k = sc.NextInt();
        int[] a = sc.IntArray();

        /*
         * iの値段a_i
         *
         * iの値段を最大kまで+-できる
         *
         * 全部同じｎ
         */

        int min = a.Min();
        int max = a.Max();

        if (max > min + 2 * k)
        {
            Console.WriteLine("-1");
            return;
        }

        Console.WriteLine(min + k);
    }

    public static void Main(string[] args) => new Program().Solve();
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            if (_index >= _line.Length)
            {
                string s;
                do
                {
                    s = Console.ReadLine();
                } while (s.Length == 0);

                _line = s.Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public string ReadLine()
        {
            _index = _line.Length;
            return Console.ReadLine();
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            string s = Console.ReadLine();
            _line = s.Length == 0 ? new string[0] : s.Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


using System;
using System.IO;
using System.Security.AccessControl;
using System.Text;

namespace Contest
{
    class Program
    {
        private Scanner sc;
        public void Solve()
        {
            sc = new Scanner();
            int q = sc.NextInt();

            var sb = new StringBuilder();
            for (int i = 0; i < q; i++)
            {
                sb.AppendLine(Query().ToString());
            }
            Console.Write(sb.ToString());
        }

        private int Query()
        {
            int n = sc.NextInt();
            int k = sc.NextInt();
            int min = -1;
            int max = int.MaxValue;
            int[] a = sc.IntArray();
            for (int i = 0; i < n; i++)
            {
                int nMin = a[i] - k;
                int nMax = a[i] + k;

                if (nMin > max || min > nMax)
                {
                    return -1;
                }

                min = Math.Max(min, nMin);
                max = Math.Min(max, nMax);
            }

            return max;
        }

        static void Main() => new Program().Solve();
    }
}

class Scanner
{
    public Scanner()
    {
        _stream = new StreamReader(Console.OpenStandardInput());
        _pos = 0;
        _line = new string[0];
        _separator = ' ';
    }
    private readonly char _separator;
    private readonly StreamReader _stream;
    private int _pos;
    private string[] _line;
    #region get a element
    public string Next()
    {
        if (_pos >= _line.Length)
        {
            _line = _stream.ReadLine().Split(_separator);
            _pos = 0;
        }
        return _line[_pos++];
    }
    public int NextInt()
    {
        return int.Parse(Next());
    }
    public long NextLong()
    {
        return long.Parse(Next());
    }
    public double NextDouble()
    {
        return double.Parse(Next());
    }
    #endregion
    #region convert array
    private int[] ToIntArray(string[] array)
    {
        var result = new int[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            result[i] = int.Parse(array[i]);
        }

        return result;
    }
    private long[] ToLongArray(string[] array)
    {
        var result = new long[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            result[i] = long.Parse(array[i]);
        }

        return result;
    }
    private double[] ToDoubleArray(string[] array)
    {
        var result = new double[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            result[i] = double.Parse(array[i]);
        }

        return result;
    }
    #endregion
    #region get array
    public string[] Array()
    {
        if (_pos >= _line.Length)
            _line = _stream.ReadLine().Split(_separator);
        _pos = _line.Length;
        return _line;
    }
    public int[] IntArray()
    {
        return ToIntArray(Array());
    }
    public long[] LongArray()
    {
        return ToLongArray(Array());
    }
    public double[] DoubleArray()
    {
        return ToDoubleArray(Array());
    }
    #endregion
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Obrabotka_1
{

    class Program
    {
        static void Main(string[] args)
        {
            int q = int.Parse(Console.ReadLine());
            int[] input;
            int[] price;
            int n;
            int k;
            int min;
            int maxResult;
            int[] results = new int[q];
            for (int counter = 0; counter < q; counter++)
            {
                input = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
                n = input[0];
                k = input[1];
                price = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
                min = price.Min();
                maxResult = min + k;
                results[counter] = maxResult;
                for(int i = 0; i < n; i++)
                {
                    if (Math.Abs(price[i] - maxResult) > k)
                    {
                        results[counter] = -1;
                        break;
                    }
                }
            }
            Console.WriteLine(String.Join("\n", results));

        }
}
}


using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using static System.Console;
using static System.Math;

namespace Olymp
{
  public class ProblemSolver
  {
    private readonly Tokenizer input;

    public void Solve()
    {
      var q = input.ReadInt();
      for (int i = 0; i < q; i++)
      {
        var (n, k) = input.Read2Int();
        var a = input.ReadIntArray(n);
        var min = a.Min();
        var max = a.Max();
        WriteLine(max - min > 2 * k ? -1 : min + k);
      }
    }

    public ProblemSolver(TextReader input)
    {
      this.input = new Tokenizer(input);
    }
  }

  #region Service classes

  public class Tokenizer
  {
    private readonly TextReader reader;

    public string ReadToEnd()
    {
      return reader.ReadToEnd();
    }

    public int ReadInt()
    {
      var c = SkipWS();
      if (c == -1)
        throw new EndOfStreamException();
      var isNegative = false;
      if (c == '-' || c == '+')
      {
        isNegative = c == '-';
        c = reader.Read();
        if (c == -1)
          throw new EndOfStreamException("Digit expected, but end of stream occurs");
      }

      if (!char.IsDigit((char)c))
        throw new InvalidOperationException($"Digit expected, but was: '{(char)c}'");
      var result = (char)c - '0';
      c = reader.Read();
      while (c > 0 && !char.IsWhiteSpace((char)c))
      {
        if (!char.IsDigit((char)c))
          throw new InvalidOperationException($"Digit expected, but was: '{(char)c}'");
        result = result * 10 + (char)c - '0';
        c = reader.Read();
      }

      if (isNegative)
        result = -result;
      return result;
    }

    public string ReadLine()
    {
      return reader.ReadLine();
    }

    public long ReadLong()
    {
      return long.Parse(ReadToken());
    }

    public double ReadDouble()
    {
      return double.Parse(ReadToken(), CultureInfo.InvariantCulture);
    }

    public int[] ReadIntArray(int n)
    {
      var a = new int[n];
      for (var i = 0; i < n; i++)
        a[i] = ReadInt();
      return a;
    }

    public (int, int) Read2Int() =>
      (ReadInt(), ReadInt());

    public (int, int, int) Read3Int() =>
      (ReadInt(), ReadInt(), ReadInt());

    public (int, int, int, int) Read4Int() =>
      (ReadInt(), ReadInt(), ReadInt(), ReadInt());

    public long[] ReadLongArray(int n)
    {
      var a = new long[n];
      for (var i = 0; i < n; i++)
        a[i] = ReadLong();
      return a;
    }

    public double[] ReadDoubleArray(int n)
    {
      var a = new double[n];
      for (var i = 0; i < n; i++)
        a[i] = ReadDouble();
      return a;
    }

    public string ReadToken()
    {
      var c = SkipWS();
      if (c == -1)
        return null;
      var sb = new StringBuilder();
      while (c > 0 && !char.IsWhiteSpace((char)c))
      {
        sb.Append((char)c);
        c = reader.Read();
      }

      return sb.ToString();
    }

    private int SkipWS()
    {
      var c = reader.Read();
      if (c == -1)
        return c;
      while (c > 0 && char.IsWhiteSpace((char)c))
        c = reader.Read();
      return c;
    }

    public Tokenizer(TextReader reader)
    {
      this.reader = reader;
    }
  }

  internal class Program
  {
    public static void Main()
    {
      var solver = new ProblemSolver(In);
      solver.Solve();
    }
  }

  #endregion
}


using System;
class Program
{
    static void Main()
    {
        Func<int[]> r = () => Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
        var n = r();
        while (n[0]-- > 0)
        {
            var nk = r();
            var a = r();
            Array.Sort(a);
            Console.WriteLine((a[nk[0] - 1] - a[0] > nk[1] * 2) ? -1 : a[0] + nk[1]);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B
{
    class Program
    {
        static void Main(string[] args)
        {
            int q = Convert.ToInt32(Console.ReadLine());
            int[][] mas = new int[q][];
            for (int i = 0; i < q; i++)
            {
                string[] str = Console.ReadLine().Split(' ');
                int n = Convert.ToInt32(str[0]);
                int k = Convert.ToInt32(str[1]);
                mas[i] = new int[n + 1];
                mas[i][n] = int.MaxValue;
                string[] str2 = Console.ReadLine().Split(' ');
                for (int j = 0; j < str2.Length; j++)
                {
                    mas[i][j] = Convert.ToInt32(str2[j]);
                }
                Array.Sort(mas[i]);
                mas[i][n] = k;
            }
            int[] res = new int[q];
            for (int i = 0; i < q; i++)
            {
                int n = mas[i].Length - 1;
                int k = mas[i][n];
                int max = k + mas[i][n - 1];
                int min = mas[i][n - 1] - k;
                if (min < 1)
                {
                    min = 1;
                }
                bool found = false;
                while (max >= min)
                {
                    if (mas[i][0] + k >= max)
                    {
                        found = true;
                        break;
                    }
                    max--;
                }
                if (!found)
                {
                    Console.WriteLine(-1);
                }
                else
                {
                    Console.WriteLine(max);
                }
            }
            //Console.ReadKey();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B
{
    class Program
    {
        static void Main(string[] args)
        {
            int q = Convert.ToInt32(Console.ReadLine());
            int[][] mas = new int[q][];
            for (int i = 0; i < q; i++)
            {
                string[] str = Console.ReadLine().Split(' ');
                int n = Convert.ToInt32(str[0]);
                int k = Convert.ToInt32(str[1]);
                mas[i] = new int[n + 1];
                mas[i][n] = int.MaxValue;
                string[] str2 = Console.ReadLine().Split(' ');
                for (int j = 0; j < str2.Length; j++)
                {
                    mas[i][j] = Convert.ToInt32(str2[j]);
                }
                Array.Sort(mas[i]);
                mas[i][n] = k;
            }
            int[] res = new int[q];
            for (int i = 0; i < q; i++)
            {
                int n = mas[i].Length - 1;
                int k = mas[i][n];
                /*int max = k + mas[i][n - 1];
                int min = mas[i][n - 1] - k;
                if (min < 1)
                {
                    min = 1;
                }
                bool found = false;*/
                if (mas[i][0] + k >= mas[i][n - 1] - k)
                {
                    Console.WriteLine(mas[i][0] + k);
                }
                else
                {
                    Console.WriteLine(-1);
                }
                /*while (max >= min)
                {
                    if (mas[i][0] + k >= max)
                    {
                        found = true;
                        break;
                    }
                    max--;
                }
                if (!found)
                {
                    Console.WriteLine(-1);
                }
                else
                {
                    Console.WriteLine(max);
                }*/
            }
            //Console.ReadKey();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
             int m=int.Parse(Console.ReadLine());

             for(int j=0;j<m;j++)
             {
                  bool f=false;
                  string[]y=Console.ReadLine().Split(' ');
                  string[]y1=Console.ReadLine().Split(' ');
                  int n=int.Parse(y[0]);
                  int k=int.Parse(y[1]);
                  int[]a=new int[n];
                  for(int i=0;i<n;i++)
                  a[i]=int.Parse(y1[i]);
                  int max=a.Min()+k;
                  for(int i=0;i<n;i++)
                  if(a[i]-max>k)
                  f=true;
                  if(f)
                  Console.WriteLine(-1);
                  else
                  Console.WriteLine(max);

             }
        }
    }
}


using System;

class _1183B
{
	static void Main()
	{
		int q = int.Parse(Console.ReadLine());
		int[] anss = new int[q];
		for (int i = 0; i < q; ++i)
		{
			int[] nk = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
			int n = nk[0];
			int k = nk[1];
			int[] a = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

			int min = int.MaxValue;
			int max = 0;
			for (int j = 0; j < n; ++j)
			{
				min = Math.Min(min, a[j]);
				max = Math.Max(max, a[j]);
			}
			int average = (min + max) >> 1;
			anss[i] = average - min > k || max - average > k ? -1: min + k;
		}

		Console.WriteLine(string.Join("\r\n", anss));
	}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Code
{
    class Program
    {
        static string Read() { var sb = new StringBuilder(); var c = (char)Console.Read(); while (c != ' ' && c != '\n') { sb.Append(c); c = (char)Console.Read(); } return sb.ToString(); }
        static int Ri() { return int.Parse(Read()); }
        static int[] RIA(int n) { var x = new int[n]; for (int i = 0; i < n; i++) x[i] = int.Parse(Read()); return x; }
        static int[] RIAZS(int n, int l) { var x = new int[n + l]; for (int i = l; i < n + l; i++) x[i] = int.Parse(Read()); return x; }
        static long Rl() { return long.Parse(Read()); }
        static long[] RLA(int n) { var x = new long[n]; for (int i = 0; i < n; i++) x[i] = long.Parse(Read()); return x; }

        static void Main(string[] args)
        {
            int q = Ri();
            int qi = q;
            int[] ans = new int[q];
            for (; q > 0; q--)
            {
                int [] inp = RIA(2);
                int min = 100000001;
                int max = 0;
                int[] dat = RIA(inp[0]);
                for (int i = 0; i < inp[0]; i++)
                {
                    if (min > dat[i])
                        min = dat[i];
                    if (max < dat[i])
                        max = dat[i];
                }
                if (min + inp[1] >= max - inp[1])
                    ans[qi-q] = min + inp[1];
                else
                    ans[qi - q] = -1;
            }
            for (int i = 0; i < qi; i++)
                Console.WriteLine(ans[i]);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ravnijeceni
{
    class Program
    {
        static void Main(string[] args)
        {
            var q = int.Parse(Console.ReadLine());
            for (var i = 1; i <= q; i++)
            {
                string[] s = Console.ReadLine().Split();
                var k = int.Parse(s[1]);

                var a = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();

                var min = a.Min();
                var max = a.Max();

                if (max-min<2*k)
                {
                    Console.WriteLine(-1);
                }
                else
                {
                    Console.WriteLine(min + k);
                }
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ravnijeceni
{
    class Program
    {
        static void Main(string[] args)
        {
            var q = int.Parse(Console.ReadLine());
            for (var i = 1; i <= q; i++)
            {
                string[] s = Console.ReadLine().Split();
                var k = int.Parse(s[1]);

                var a = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();

                var min = a.Min();
                var max = a.Max();

                if (max-min>2*k)
                {
                    Console.WriteLine(-1);
                }
                else
                {
                    Console.WriteLine(min + k);
                }
            }
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Text;

namespace Equalize_Prices
{
    internal class Program
    {
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            for (int i = Next() - 1; i >= 0; i--)
            {
                writer.WriteLine(Solve());
            }
            writer.Flush();
        }

        private static int Solve()
        {
            int n = Next();
            int k = Next();

            var nn = new int[n];
            for (int i = 0; i < n; i++)
            {
                nn[i] = Next();
            }
            int min = nn.Min();
            int ans = min + k;
            if (ans + k >= nn.Max())
                return ans;

            return -1;
        }

        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication15
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = Console.ReadLine();
            var n = int.Parse(input);
            var sb = new StringBuilder();
            for (int i = 0; i < n; i++)
            {
                input = Console.ReadLine();
                var arr = input.Split();

                var c = int.Parse(arr[0]);
                var x = int.Parse(arr[1]);

                input = Console.ReadLine();
                arr = input.Split();
                var arrInt = new int[c];
                //var d = new HashSet<int>();
                for (int j = 0; j < c; j++)
                {
                    arrInt[j] = int.Parse(arr[j]);
                    //d.Add(arrInt[j]);
                }
                var min = arrInt.Min();
                var max = arrInt.Max();

                var diff = max - min;
                if (diff <= 2 * x)
                {
                    sb.Append(string.Format("{0}\n", min + x));
                }
                else
                {
                    sb.Append("-1\n");
                }

            }
            Console.WriteLine(sb);
            //Console.ReadLine();
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class TEST{
	static void Main(){
		Sol mySol =new Sol();
		mySol.Solve();
	}
}

class Sol{
	public void Solve(){
		for(;Q>0;Q--){
			var d = ria();
			N = d[0]; K = d[1];
			A = rla();
			Array.Sort(A);
			if(A[0] + K < A[N-1] - K){
				Console.WriteLine(-1);
			} else {
				Console.WriteLine(A[0] + K);
			}
		}

	}
	int N;
	long K;
	long[] A;
	int Q;
	public Sol(){
		Q = ri();
	}

	static String rs(){return Console.ReadLine();}
	static int ri(){return int.Parse(Console.ReadLine());}
	static long rl(){return long.Parse(Console.ReadLine());}
	static double rd(){return double.Parse(Console.ReadLine());}
	static String[] rsa(char sep=' '){return Console.ReadLine().Split(sep);}
	static int[] ria(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>int.Parse(e));}
	static long[] rla(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>long.Parse(e));}
	static double[] rda(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>double.Parse(e));}
}


//#define EXTENDSTACKSIZE

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

         namespace CF
{
    internal class Program
    {
        private const int stackSize = 64 * 1024 * 1024;

        private static void Run()
        {
            using (var sr = new InputReader(Console.In))
//            using (var sr = new InputReader(new StreamReader("input.txt")))
            using (var sw = Console.Out)
//            using (var sw = new StreamWriter("output.txt"))
            using (var task = new Task(sr, sw)) {
                task.Solve();
//                Console.ReadKey();
            }
        }

        private static void Main(string[] args)
        {
#if EXTENDSTACKSIZE
            var threadStart = new ThreadStart(Run);
            var thread = new Thread(threadStart, stackSize);
            thread.Start();
            thread.Join();
#else
            Run();
#endif
        }
    }

    internal class Task : IDisposable
    {
        private readonly InputReader sr;
        private readonly TextWriter sw;
        private bool isDispose;

        public Task(InputReader sr, TextWriter sw)
        {
            this.sr = sr;
            this.sw = sw;
        }

        public void Solve()
        {
            var q = sr.NextInt32();
            var answers = new StringBuilder();
            for (var t = 0; t < q; t++)
            {
                var n = sr.NextInt32();
                var k = sr.NextInt32();
                var items = sr.ReadArrayOfInt32();
                var results = new List<int>();
                for (var i = 0; i < items.Length; i++)
                {
                    var curr = items[i] + k;
                    var can = true;
                    for (var j = 0; j < items.Length; j++)
                    {
                        if (Math.Abs(items[j] - curr) > k)
                        {
                            can = false;
                            break;
                        }
                    }

                    if (can)
                    {
                        results.Add(curr);
                    }
                }

                var canZero = true;
                for (var j = 0; j < items.Length; j++)
                {
                    if (items[j] > k)
                    {
                        canZero = false;
                        break;
                    }
                }

                if (canZero)
                {
                    results.Add(0);
                }

                if (results.Count == 0)
                {
                    answers.AppendLine("-1");
                }
                else
                {
                    answers.AppendLine(results.Max().ToString());
                }
            }

            sw.Write(answers);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!isDispose) {
                if (disposing) {
                    if(sr != null)
                        sr.Dispose();

                    if(sw != null)
                        sw.Dispose();
                }

                isDispose = true;
            }
        }
    }
}

internal class InputReader : IDisposable
{
    private bool isDispose;
    private readonly TextReader sr;
    private string[] buffer;
    private int seek;

    public InputReader(TextReader stream)
    {
        sr = stream;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public string NextString()
    {
        var result = sr.ReadLine();
        return result;
    }

    public int NextInt32()
    {
        return Int32.Parse(ReadNextToken());
    }

    private string ReadNextToken()
    {
        if (buffer == null || seek == buffer.Length) {
            seek = 0;
            buffer = NextSplitStrings();
        }

        return buffer[seek++];
    }

    public long NextInt64()
    {
        return Int64.Parse(ReadNextToken());
    }

    public int[] ReadArrayOfInt32()
    {
        return ReadArray(Int32.Parse);
    }

    public long[] ReadArrayOfInt64()
    {
        return ReadArray(Int64.Parse);
    }

    public string[] NextSplitStrings()
    {
        return NextString()
            .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public T[] ReadArray<T>(Func<string, CultureInfo, T> func)
    {
        return NextSplitStrings()
            .Select(s => func(s, CultureInfo.InvariantCulture))
            .ToArray();
    }

    public T[] ReadArrayFromString<T>(Func<string, CultureInfo, T> func, string str)
    {
        return
            str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => func(s, CultureInfo.InvariantCulture))
                .ToArray();
    }

    protected void Dispose(bool dispose)
    {
        if (!isDispose)
        {
            if (dispose)
                sr.Close();

            isDispose = true;
        }
    }

    ~InputReader()
    {
        Dispose(false);
    }
}


//#define EXTENDSTACKSIZE

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

         namespace CF
{
    internal class Program
    {
        private const int stackSize = 64 * 1024 * 1024;

        private static void Run()
        {
            using (var sr = new InputReader(Console.In))
//            using (var sr = new InputReader(new StreamReader("input.txt")))
            using (var sw = Console.Out)
//            using (var sw = new StreamWriter("output.txt"))
            using (var task = new Task(sr, sw)) {
                task.Solve();
//                Console.ReadKey();
            }
        }

        private static void Main(string[] args)
        {
#if EXTENDSTACKSIZE
            var threadStart = new ThreadStart(Run);
            var thread = new Thread(threadStart, stackSize);
            thread.Start();
            thread.Join();
#else
            Run();
#endif
        }
    }

    internal class Task : IDisposable
    {
        private readonly InputReader sr;
        private readonly TextWriter sw;
        private bool isDispose;

        public Task(InputReader sr, TextWriter sw)
        {
            this.sr = sr;
            this.sw = sw;
        }

        public void Solve()
        {
            var q = sr.NextInt32();
            var answers = new StringBuilder();
            for (var t = 0; t < q; t++)
            {
                var n = sr.NextInt32();
                var k = sr.NextInt32();
                var items = sr.ReadArrayOfInt32();
                var results = new List<int>();
                for (var i = 0; i < items.Length; i++)
                {
                    var curr = items[i] + k;
                    var can = true;
                    for (var j = 0; j < items.Length; j++)
                    {
                        if (Math.Abs(items[j] - curr) > k)
                        {
                            can = false;
                            break;
                        }
                    }

                    if (can)
                    {
                        results.Add(curr);
                    }
                }

                if (results.Count == 0)
                {
                    answers.AppendLine("-1");
                }
                else
                {
                    answers.AppendLine(results.Max().ToString());
                }
            }

            sw.Write(answers);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!isDispose) {
                if (disposing) {
                    if(sr != null)
                        sr.Dispose();

                    if(sw != null)
                        sw.Dispose();
                }

                isDispose = true;
            }
        }
    }
}

internal class InputReader : IDisposable
{
    private bool isDispose;
    private readonly TextReader sr;
    private string[] buffer;
    private int seek;

    public InputReader(TextReader stream)
    {
        sr = stream;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public string NextString()
    {
        var result = sr.ReadLine();
        return result;
    }

    public int NextInt32()
    {
        return Int32.Parse(ReadNextToken());
    }

    private string ReadNextToken()
    {
        if (buffer == null || seek == buffer.Length) {
            seek = 0;
            buffer = NextSplitStrings();
        }

        return buffer[seek++];
    }

    public long NextInt64()
    {
        return Int64.Parse(ReadNextToken());
    }

    public int[] ReadArrayOfInt32()
    {
        return ReadArray(Int32.Parse);
    }

    public long[] ReadArrayOfInt64()
    {
        return ReadArray(Int64.Parse);
    }

    public string[] NextSplitStrings()
    {
        return NextString()
            .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public T[] ReadArray<T>(Func<string, CultureInfo, T> func)
    {
        return NextSplitStrings()
            .Select(s => func(s, CultureInfo.InvariantCulture))
            .ToArray();
    }

    public T[] ReadArrayFromString<T>(Func<string, CultureInfo, T> func, string str)
    {
        return
            str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => func(s, CultureInfo.InvariantCulture))
                .ToArray();
    }

    protected void Dispose(bool dispose)
    {
        if (!isDispose)
        {
            if (dispose)
                sr.Close();

            isDispose = true;
        }
    }

    ~InputReader()
    {
        Dispose(false);
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {
            var q = int.Parse(Console.ReadLine());

            while(--q >= 0)
            {
                var nk = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                var n = nk[0];
                var k = nk[1];
                var prices = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                var minPrice = prices.Min();
                var maxPrice = prices.Max();

                if (maxPrice - minPrice > k)
                    Console.WriteLine(-1);
                else
                    Console.WriteLine(minPrice + k);

            }

        }

    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {
            var q = int.Parse(Console.ReadLine());

            while(--q >= 0)
            {
                var nk = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                var n = nk[0];
                var k = nk[1];
                var prices = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                var minPrice = prices.Min();
                var maxPrice = prices.Max();

                if (maxPrice - minPrice > 2*k)
                    Console.WriteLine(-1);
                else
                    Console.WriteLine(minPrice + k);

            }

        }

    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        { List<long> lis = new List<long>();
            int q =int.Parse(Console.ReadLine());
            for (int i = 0; i < q; i++) {
                long[] nk = Console.ReadLine().Split().Select(x => long.Parse(x)).ToArray();
                long[] mas = Console.ReadLine().Split().Select(x => long.Parse(x)).ToArray();
                Array.Sort(mas);
                long raz = mas[mas.Count() - 1] - mas[0];
                if (2*nk[1] - raz >= 0) {
                    lis.Add(mas[0]+nk[1]);

                }else
                    lis.Add(-1);

            }
            foreach (var n in lis) {
                Console.WriteLine(n);
            }

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace CF_570
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var q = ReadInt();
            for (var tcase = 0; tcase < q; tcase++)
            {
                var array = ReadIntArray();
                var n = array[0];
                var k = array[1];
                array = ReadIntArray().OrderBy(i=>i).ToList();
                if(array[n - 1] - array[0] > k * 2)
                    Console.WriteLine("-1");
                else
                    Console.WriteLine(array[0] + k);
            }

        }

        private static int ReadInt()
        {
            return Convert.ToInt32(Console.ReadLine());
        }
        private static List<int> ReadIntArray()
        {
            return Console.ReadLine().Split().Select(s=>Convert.ToInt32(s)).ToList();
        }
    }
}


/* Date: 28.06.2019  *  Time: 21:45 */
//
// https://docs.microsoft.com/en-us/dotnet/api/system.tuple-8?redirectedfrom=MSDN&view=netframework-4.7.2
//
//

/*
�	fflush(stdout) � ����� C++;
�	System.out.flush() � Java;
�	stdout.flush() � Python;
�	flush(output) � Pascal;

*/

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

class Example
{
	public static void Main (string[] args)
	{
# if ( ! ONLINE_JUDGE )
		StreamReader sr = new StreamReader ("C:\\TRR\\2019\\Task\\07 Codeforces\\040\\B.TXT");
		StreamWriter sw = new StreamWriter ("C:\\TRR\\2019\\Task\\07 Codeforces\\040\\OUTPUT.OUT");
# endif

		NumberFormatInfo nfi = NumberFormatInfo.InvariantInfo;

		int q;

# if ( ONLINE_JUDGE )
		q = int.Parse (Console.ReadLine ());
# else
		q = int.Parse (sr.ReadLine ());
		sw.WriteLine ("*** TEST = " + q);
# endif

		for ( int qqq=0; qqq < q; qqq++ )
		{
			string s, s1;

# if ( ONLINE_JUDGE )
			s = (Console.ReadLine ());
			s1 = (Console.ReadLine ());
# else
			s = (sr.ReadLine ());
			s1 = (sr.ReadLine ());
			sw.WriteLine ("*** " + s);
			sw.WriteLine ("*** " + s1);
# endif

			string [] ss = s.Split (' ');
			int n = int.Parse (ss [0]);
			int k = int.Parse (ss [1]);

			string [] ss1 = s1.Split (' ');
			int [] b = new int [n];

			int max = 0, min = 1000000000;
			for ( int i=0; i < n; i++ )
			{
				b [i] = int.Parse (ss1 [i]);
				if ( b [i] > max )
					max = b [i];
				if ( b [i] < min )
					min = b [i];
			}

# if ( ! ONLINE_JUDGE )
			sw.WriteLine ("*** max = " + max);
			sw.WriteLine ("*** min = " + min);
# endif

			int m = 0;
			if ( max - min > k + k )
				m = -1;
			else
				m = min + k;

# if ( ONLINE_JUDGE )
			Console.WriteLine (m);
# else
			sw.WriteLine (m);
# endif

		}

# if ( ! ONLINE_JUDGE )
		sw.Close ();
# endif
	}
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Test
{

    static void insertionElement(List<int> array, int item) {
    int beginIndex = 0;
    int endIndex = array.Count - 1;

    int middle = 0;
    while (endIndex - beginIndex > 0) {
      middle = (beginIndex + endIndex) / 2;
      if (array.ElementAt(middle) > item) {
        endIndex = middle;
      } else {
        beginIndex = middle + 1;
      }
    }

    if (array.Count > beginIndex && array.ElementAt(beginIndex) < item) beginIndex++;
    array.Insert(beginIndex, item);
  }

    static void Swap<T>(ref T lhs, ref T rhs){
        T temp;
        temp = lhs;
        lhs = rhs;
        rhs = temp;
    }

    static ulong ks2(ulong n){
        ulong ans = 0;
        while(n!=0) {
            ans += (n%10);
            n /= 10;
        }
        return ans;
    }

    static int boob(int n){
	    int zza=0;
	    while(n>0){
	        int sds = n%10;
		    zza+=sds;
		    n/=10;
	    }
	    return zza;
    }

	public static void Main()
	{
	    long tc = Convert.ToInt64(Console.ReadLine());
	    while(tc-->0){
	        long n,k;
	        string line = Console.ReadLine();
	        string[] lineSplitter = line.Split(' ');
	        lineSplitter = line.Split(' ');
	        n = long.Parse(lineSplitter[0]);
	        k = long.Parse(lineSplitter[1]);
	        long twice = 2*k;
	        long[] vector = new long[n];
	        line = Console.ReadLine();
	        lineSplitter = line.Split(' ');
	        for(long i=0;i<n;i++){
                vector[i] = Int64.Parse(lineSplitter[i]);
            }
            Array.Sort(vector);
            long first = vector[n-1];
            long second = vector[0];
            long spac = first-second;

            if(spac>twice){
                Console.WriteLine("-1");
            }
            else if(spac<=twice && spac>=k){
                spac=spac-k;
                vector[n-1]-=spac;
                Console.WriteLine(vector[n-1]);
            }
            else if(spac<k){
                vector[0]+=k;
                Console.WriteLine(vector[0]);
            }
	    }
	}
}


using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;

namespace ProjectContest
{
    class Test
    {

        static void Main()
        {
            int q = Convert.ToInt32(Console.ReadLine());

            while (q-- > 0)
            {
                var nk = Array.ConvertAll(Console.ReadLine().Split(), Convert.ToInt32);
                int n = nk[0], k = nk[1];
                var a = Array.ConvertAll(Console.ReadLine().Split(), Convert.ToInt32);
                Array.Sort(a);
                int kq = (a[0] + a[n - 1]) / 2;
                if (Math.Abs(a[0] - kq) <= k && Math.Abs(a[n - 1] - kq) <= k)
                    Console.WriteLine(Math.Max(kq,a[0]+k));
                else Console.WriteLine(-1);
            }

        }
    }
}


using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;

namespace ProjectContest
{
    class Test
    {

        static void Main()
        {
            int q = Convert.ToInt32(Console.ReadLine());

            while (q-- > 0)
            {
                var nk = Array.ConvertAll(Console.ReadLine().Split(), Convert.ToInt32);
                int n = nk[0], k = nk[1];
                var a = Array.ConvertAll(Console.ReadLine().Split(), Convert.ToInt32);
                Array.Sort(a);
                int kq = (a[0] + a[n - 1]) / 2;
                if (Math.Abs(a[0] - kq) <= k && Math.Abs(a[n - 1] - kq) <= k)
                    Console.WriteLine(kq);
                else Console.WriteLine(-1);
            }

        }
    }
}


using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;

class MyClass
{
    public static void Solve()
    {
        var q = int.Parse(Console.ReadLine());
        for (int _i = 0; _i < q; _i++)
        {
            var input = Console.ReadLine().Split().Select(int.Parse).ToArray();
            var n = input[0];
            var k = input[1];
            var a = Console.ReadLine().Split().Select(int.Parse).ToArray();
            var min = a.Min();
            var max = a.Max();
            if (min + k < max - k)
            {
                Console.WriteLine(-1);
            }
            else
            {
                Console.WriteLine(min + k);
            }
        }
    }

    public static void Main()
    {
        var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
        Console.SetOut(sw);
        Solve();
        Console.Out.Flush();
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var q = int.Parse(Console.ReadLine());
            for (int i = 0; i < q; i++)
            {
                var data = Console.ReadLine().Split().Select(int.Parse).ToArray();
                var n = data[0];
                var k = data[1];
                data = Console.ReadLine().Split().Select(int.Parse).ToArray();
                if (data.Max() - data.Min() > 2*k)
                {
                    Console.WriteLine(-1);
                    continue;
                }
                var B = data.Min() + k;
                Console.WriteLine(B);
            }
        }
    }
}


/*

 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

public class Solver
{
    public void Solve()
    {
        int queries = ReadInt();
        for (int query = 0; query < queries; query++)
        {
            int n = ReadInt();
            int k = ReadInt();
            int[] a = ReadIntArray();
            int min_ = int.MaxValue;
            int max_ = int.MinValue;
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] < min_)
                    min_ = a[i];
                if (a[i] > max_)
                    max_ = a[i];
            }
            if (min_ + k >= max_ - k)
                Write(min_+k);
            else
                Write(-1);
        }
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
#if DEBUG
        Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
        // 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
        {
#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
}


//spnauti-rusT
use std::io::*;
use std::str::{self,*};
use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_macros)]
macro_rules! m {
    ($c:tt, $x:expr, $y:expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
#[allow(unused_macros)]
macro_rules! l {
    ($($v:ident),* = $i:ident.$f:ident $a:tt) => {
        $( let $v = $i.$f$a; )*
    };
    ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {
        $( let $v:$t = $i.$f$a; )*
    };
}
struct WordReader<'a> { it : SplitAsciiWhitespace<'a> }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).ok();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, stdin())
    }
    fn sl(&mut self) ->  &str { self.it.next().unwrap() }
    fn bs(&mut self) -> &[u8] { self.sl().as_bytes()    }
    fn s(&mut self) -> String { String::from(self.sl()) }
    fn i(&mut self) ->    i32 { self.p()                }
    fn f(&mut self) ->    f64 { self.p()                }
    fn u(&mut self) ->  usize { self.p()                }
    fn sk(&mut self, n: usize) { self.it.nth(n - 1); }
    fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> {
        self.ip(n).into_iter()
    }
    fn vi(&mut self, n: usize) -> Vec<i32> {
        self.vp::<i32>(n)
    }
    fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
        self.sl().parse::<T>().unwrap()
    }
    fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
        self.vp(n).into_iter()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}
//------------------- End rusT

fn main() {
    let mut bin = String::new();
    let mut input = WordReader::from_stdin(&mut bin);
    let mut bout = BufWriter::new(stdout());

    let q = input.u();
    for _ in 0..q {
        let n = input.u();
        let k = input.i();
        let a = input.vi(n);
        let min = *a.iter().min().unwrap();
        let max = *a.iter().max().unwrap();
        let sol = if max - min > 2 * k {-1} else {min + k};
        writeln!(bout, "{}", sol).ok();
    }
}


#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(dead_code)]

use std::char::*;
use std::cmp::*;
use std::collections::*;
use std::io::*;
use std::str::FromStr;

macro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);}}
macro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }
macro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }
macro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

use std::f64;

fn min<T: PartialOrd>(a:T, b:T) -> T {
    if a < b { a }
    else { b }
}

fn max<T: PartialOrd>(a:T, b:T) -> T {
    if a < b { b }
    else { a }
}

use std::hash::Hash;
fn inc<T: Hash+Ord>(map:&mut BTreeMap<T,i64>, key:T) {
    let count = map.entry(key).or_insert(0);
    *count += 1;
}

fn digit(ch: char) -> i64 {
    return (ch as u8 - b'0') as i64
}

const MAX:usize = 30;
const INF:i64 = std::i64::MAX;
const MOD:i64 = 1e9 as i64 + 7;

fn func(n:i64) -> i64 {
    if n==0 { return 0; }
    n%10 + func(n/10)
}

fn main() {
    let t:usize = read();

    'outer: for _ in 0..t {
        let n:usize = read();
        let k:i64 = read();
        let a:Vec<i64> = (0..n).map(|_| read()).collect();

        let mut mn = INF;
        let mut mx = 0;
        for i in 0..n {
            mn = min(mn, a[i]+k);
            mx = max(mx, max(a[i]-k,0));
        }
        //debug!(mn,mx);
        if mn < mx {
            println!("-1");
        } else {
            println!("{}", mn);
        }
    }
}

/*

*/


use std::io;
use std::cmp::{max, min};

fn main() -> io::Result<()> {
    let stdin = io::stdin();
    let mut input = String::new();
    stdin.read_line(&mut input)?;

    let q: u8 = input.trim().parse().unwrap();
    for _ in 1..q+1 {
        let mut input = String::new();
        stdin.read_line(&mut input)?;

        let mut l: Vec<i32> = input.split_whitespace()
            .map(|x| x.parse().unwrap()).collect();
        let _n = l[0];
        let k = l[1];

        // println!("n {} k {}", n, k);

        let mut input = String::new();
        stdin.read_line(&mut input)?;
        let prices = input.split_whitespace()
            .map(|x| x.trim().parse::<i32>().unwrap());

        let mut sup = std::i32::MAX;
        let mut inf = 0;
        let mut breaked = false;
        for price in prices {
            //print!("{} ", price);
            if inf > price + k || sup < max(0, price - k) {
                println!("-1");
                breaked = true;
                break;
            }

            sup = min(price + k, sup);
            inf = max(price - k, inf);
        }

        if !breaked {
            println!("{}", sup);
        }

    }

    Ok(())
}


use std::io::stdin;

macro_rules! read {
    ($v: ident : $t: ty) => {
        let mut buf = String::new();
        let _ = stdin().read_line(&mut buf).expect("Failed to read input");
        let mut $v = buf.trim().trim_end().parse::<$t>().unwrap();
    };
    ($v: ident : vec $t: ty) => {
        let mut buf = String::new();
        let _ = stdin().read_line(&mut buf).expect("Failed to read input");
        let mut $v: Vec<$t> = buf
            .split_whitespace()
            .map(|x| x.trim().trim_end().parse::<$t>().unwrap())
            .collect::<Vec<$t>>();
    };
}

fn main() {
    read!(q: i32);
    while q != 0 {
        q -= 1;
        read!(x: vec i32);
        let k = x[1];
        read!(x: vec i32);
        let (mut mn, mut mx) = (10000000, -1);
        for ele in &x {
            if *ele < mn {
                mn = *ele;
            }
            if *ele > mx {
                mx = *ele;
            }
        }
        println!("{}", if mx - mn > 2 * k { -1 } else { mn + k });
    }
}


use std::io::stdin;

macro_rules! read {
    ($v: ident : $t: ty) => {
        let mut buf = String::new();
        let _ = stdin().read_line(&mut buf).expect("Failed to read input");
        let mut $v = buf.trim().trim_end().parse::<$t>().unwrap();
    };
    ($v: ident : vec $t: ty) => {
        let mut buf = String::new();
        let _ = stdin().read_line(&mut buf).expect("Failed to read input");
        let mut $v: Vec<$t> = buf
            .split_whitespace()
            .map(|x| x.trim().trim_end().parse::<$t>().unwrap())
            .collect::<Vec<$t>>();
    };
}

fn main() {
    read!(q: i32);
    while q != 0 {
        q -= 1;
        read!(x: vec i64);
        let k = x[1];
        read!(x: vec i64);
        let (mut mn, mut mx) = (100000000000000, -1);
        for ele in &x {
            if *ele < mn {
                mn = *ele;
            }
            if *ele > mx {
                mx = *ele;
            }
        }
        println!("{}", if mx - mn > 2 * k { -1 } else { mn + k });
    }
}


#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::Read;

#[allow(dead_code)]
fn getline() -> String {
    let mut ret = String::new();
    std::io::stdin().read_line(&mut ret).ok().unwrap();
    ret
}

fn get_word() -> String {
    let stdin = std::io::stdin();
    let mut stdin=stdin.lock();
    let mut u8b: [u8; 1] = [0];
    loop {
        let mut buf: Vec<u8> = Vec::with_capacity(16);
        loop {
            let res = stdin.read(&mut u8b);
            if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {
                break;
            } else {
                buf.push(u8b[0]);
            }
        }
        if buf.len() >= 1 {
            let ret = String::from_utf8(buf).unwrap();
            return ret;
        }
    }
}

#[allow(dead_code)]
fn get<T: std::str::FromStr>() -> T { get_word().parse().ok().unwrap() }

const INF: i64 = 1 << 40;

fn solve() {
    let q: usize = get();
    for _ in 0..q {
        let n: usize = get();
        let k: i64 = get();
        let a: Vec<i64> = (0..n).map(|_| get()).collect();
        let mut hi = INF;
        let mut lo = -INF;
        for &a in &a {
            hi = min(hi, a + k);
            lo = max(lo, a - k);
        }
        println!("{}", if hi < lo { -1 } else { hi });
    }
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}


package main

import (
	"fmt"
	"sort"
)

func main() {
	// var a string
	var n, q, res, k, x int
	// var x float64
	// var s string
	// scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Scanln(&q)

	for i := 0; i < q; i++ {
		fmt.Scanln(&n, &k)

		a := make([]int, n)
		m := make(map[int]int)

		for i := 0; i < n; i++ {
			fmt.Scanf("%d", &a[i])
			m[a[i]]++
		}
		fmt.Scanln(&x)

		sort.Ints(a)
		if (a[len(a)-1] - a[0]) > 2*k {
			res = -1
		} else {
			res = k + a[0]
		}
		fmt.Println(res)
		res = 0
	}

}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

func main() {
	// var a string
	var n, q, res, k, x int
	// var x float64
	// var s string
	scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Fscanln(scr, &q)

	for i := 0; i < q; i++ {
		fmt.Scanln(&n, &k)

		a := make([]int, n)
		m := make(map[int]int)

		for i := 0; i < n; i++ {
			fmt.Scanf("%d", &a[i])
			m[a[i]]++
		}
		fmt.Scanln(&x)

		sort.Ints(a)
		if (a[len(a)-1] - a[0]) > 2*k {
			res = -1
		} else {
			res = k + a[0]
		}
		fmt.Println(res)
		res = 0
	}

}


package main
import "fmt"
import "math"

func main() {
	var n, total, k int
	maxGo := int(math.Pow(10,8)-1);
	fmt.Scanln(&n)

	for x:=0; x <n ; x++{
	    fmt.Scan(&total)
	    fmt.Scan(&k)
	    a := make([]int, total)
	    min, max :=maxGo,0
    	for i := range a {
    		fmt.Scan(&a[i])
    		if a[i]< min{
    		    min = a[i]
    		}

    		if (a[i]>max){
    		    max = a[i]
    		}
    	}

    	newPrice := min + k
    	calculate := float64(max-newPrice)
    	if (newPrice <= 0 ){
    	 fmt.Println(-1)
    	}else if (int(math.Abs(calculate))<=k){
    	    fmt.Println(newPrice)
    	}else{
    	    fmt.Println(-1)
    	}
	}

    return
}


package main
import "fmt"
import "math"

func main() {
	var n, total, k int
	maxGo := int(math.Pow(10,8)-1);
	fmt.Scanln(&n)

	for x:=0; x <n ; x++{
	    fmt.Scan(&total)
	    fmt.Scan(&k)
	    a := make([]int, total)
	    min, max :=maxGo,0
    	for i := range a {
    		fmt.Scan(&a[i])
    		if a[i]< min{
    		    min = a[i]
    		}

    		if (a[i]>max){
    		    max = a[i]
    		}
    	}

    	newPrice := min + k
    	calculate := float64(max-newPrice)
    	if (int(math.Abs(calculate))<=k){
    	    fmt.Println(newPrice)
    	}else{
    	    fmt.Println(-1)
    	}
	}

    return
}


package main
import "fmt"
import "math"

func main() {
	var n, total, k int
	maxGo := int(math.Pow(10,8));
	fmt.Scanln(&n)

	for x:=0; x <n ; x++{
	    fmt.Scan(&total)
	    fmt.Scan(&k)
	    a := make([]int, total)
	    min, max :=maxGo,0
    	for i := range a {
    		fmt.Scan(&a[i])
    		if a[i]< min{
    		    min = a[i]
    		}

    		if (a[i]>max){
    		    max = a[i]
    		}
    	}

    	newPrice := min + k
    	calculate := max-newPrice
    	if (newPrice <= 0 ){
    	 fmt.Println(-1)
    	}else if (calculate<=k){
    	    fmt.Println(newPrice)
    	}else{
    	    fmt.Println(-1)
    	}
	}

    return
}


package main

import (
	"fmt"
	"sort"
)

func main() {
	var q int
	fmt.Scan(&q)

	for ; q > 0; q-- {
		var n, k int
		fmt.Scan(&n, &k)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Scan(&a[i])
		}

		sort.Ints(a)

		if a[len(a)-1]-k > a[0]+k {
			fmt.Println(-1)
		} else {
			fmt.Println(a[0] + k)
		}
	}
}


package main

import "fmt"

func main() {
	var q int
	fmt.Scan(&q)
	for ; q > 0; q-- {
		var n, k, a, min, max int64
		fmt.Scan(&n, &k)
		for ; n > 0; n-- {
			fmt.Scan(&a)
			if min == 0 || min > a {
				min = a
			}
			if max < a {
				max = a
			}
		}
		if max-min > 2*k {
			fmt.Println(-1)
		} else {
			fmt.Println(min + k)
		}
	}
}


package main

import (
	"fmt"
	"math"
)

var a [110]int
func abs(n int)int{
	if(n<=0){
		return -n;
	}
	return n;
}
func main() {
	var q int

	fmt.Scanln(&q)
	for k:=1;k<=q;k++{
		var n,k int
		fmt.Scanf("%d %d",&n,&k)

		var min,max int
		min=math.MaxInt16

		for i:=1;i<=n;i++{
			fmt.Scanf("%d",&a[i])
			if a[i]<min{
				min=a[i]
			}
			if a[i]>max{
				max=a[i]
			}

		}
		var ans2,ans3 int

		ans2=min+k;

		if max-k>0{
			ans3=max-k
		} else{
			ans3=1
		}

		if ans2>=ans3{
			fmt.Printf("%d\n",min+k)
		} else {
			fmt.Println("-1")
		}
	}

}


package main

import (
	"fmt"
	"math"
)

var a [110]int
func abs(n int)int{
	if(n<=0){
		return -n;
	}
	return n;
}
func main() {
	var q int

	fmt.Scanln(&q)
	for k:=1;k<=q;k++{
		var n,k int
		fmt.Scanf("%d %d",&n,&k)

		var min,max int
		min=math.MaxInt16

		for i:=1;i<=n;i++{
			fmt.Scanf("%d",&a[i])
			if a[i]<min{
				min=a[i]
			}
			if a[i]>max{
				max=a[i]
			}

		}
		var ans2,ans3 int

		ans2=min+k;

		ans3=max+k

		if ans2>=ans3{
			fmt.Printf("%d\n",min+k)
		} else {
			fmt.Println("-1")
		}
	}

}


package main

import (
	"fmt"
)

var a [110] int32
func abs(n int)int{
	if(n<=0){
		return -n;
	}
	return n;
}
func main() {
	var q int

	fmt.Scanln(&q)
	for k:=1;k<=q;k++{
		var n,k int32
		fmt.Scanf("%lld %lld",&n,&k)

		var min,max int32
		min=a[0]
		max=a[0]
		var i int32

		for i=1;i<=n;i++{
			fmt.Scanf("%lld",&a[i])
			if a[i]<min{
				min=a[i]
			}
			if a[i]>max{
				max=a[i]
			}

		}
		var ans2,ans3 int32

		ans2=min+k;

		ans3=max-k

		if ans2>=ans3{
			fmt.Printf("%d\n",min+k)
		} else {
			fmt.Println("-1")
		}
	}

}


package main

import (
	"fmt"
	"math"
)

var a [110] int64
func abs(n int)int{
	if(n<=0){
		return -n;
	}
	return n;
}
func main() {
	var q int

	fmt.Scanln(&q)
	for k:=1;k<=q;k++{
		var n int
		var k int64
		fmt.Scanf("%d %d",&n,&k)

		var min,max int64
		min=math.MaxInt64
		max=math.MinInt64

		for i:=1;i<=n;i++{
			fmt.Scanf("%d",&a[i])
			if a[i]<min{
				min=a[i]
			}
			if a[i]>max{
				max=a[i]
			}

		}

		if(max-min>k*2){
			fmt.Println("-1");
		}else {
			fmt.Println(min+k)
		}
	}

}


package main

import (
	"fmt"
	"math"
)

var a [110]int
func abs(n int)int{
	if(n<=0){
		return -n;
	}
	return n;
}
func main() {
	var q int

	fmt.Scanln(&q)
	for k:=1;k<=q;k++{
		var n,k int
		fmt.Scanf("%d %d",&n,&k)

		var min,max int
		min=math.MaxInt16

		for i:=1;i<=n;i++{
			fmt.Scanf("%d",&a[i])
			if a[i]<min{
				min=a[i]
			}
			if a[i]>max{
				max=a[i]
			}

		}
		var ans2,ans3 int

		ans2=min+k;

		ans3=max-k

		if ans2>=ans3{
			fmt.Printf("%d\n",min+k)
		} else {
			fmt.Println("-1")
		}
	}

}


package main

import (
	"fmt"
	"math"
)

var a [110] int64
func abs(n int)int{
	if(n<=0){
		return -n;
	}
	return n;
}
func main() {
	var q int

	fmt.Scanln(&q)
	for k:=1;k<=q;k++{
		var n int
		var k int64
		fmt.Scanf("%d %d",&n,&k)

		var min,max int64
		min=math.MaxInt64
		max=math.MinInt64

		for i:=1;i<=n;i++{
			fmt.Scan(&a[i])
			if a[i]<min{
				min=a[i]
			}
			if a[i]>max{
				max=a[i]
			}

		}

		if(max-min>k*2){
			fmt.Println("-1");
		}else {
			fmt.Println(min+k)
		}
	}

}


package main

import (
	"fmt"
	"math"
)

var a [110] int64
func abs(n int)int{
	if(n<=0){
		return -n;
	}
	return n;
}
func main() {
	var q int

	fmt.Scan(&q)
	for k:=1;k<=q;k++{
		var n int
		var k int64
		fmt.Scan(&n,&k)

		var min,max int64
		min=math.MaxInt64
		max=math.MinInt64

		for i:=1;i<=n;i++{
			fmt.Scan(&a[i])
			if a[i]<min{
				min=a[i]
			}
			if a[i]>max{
				max=a[i]
			}

		}

		if(max-min>k*2){
			fmt.Println("-1");
		}else {
			fmt.Println(min+k)
		}
	}

}


package main

import (
	"fmt"
)

var a [110] int32
func abs(n int)int{
	if(n<=0){
		return -n;
	}
	return n;
}
func main() {
	var q int

	fmt.Scanln(&q)
	for k:=1;k<=q;k++{
		var n,k int
		fmt.Scanf("%lld %lld",&n,&k)

		var min,max int32
		min=a[0]
		max=a[0]

		for i:=1;i<=n;i++{
			fmt.Scanf("%lld",&a[i])
			if a[i]<min{
				min=a[i]
			}
			if a[i]>max{
				max=a[i]
			}

		}
		var ans2,ans3 int

		ans2=min+k;

		ans3=max-k

		if ans2>=ans3{
			fmt.Printf("%d\n",min+k)
		} else {
			fmt.Println("-1")
		}
	}

}


package main

import (
	"fmt"
)

var a [110]int
func abs(n int)int{
	if(n<=0){
		return -n;
	}
	return n;
}
func main() {
	var q int

	fmt.Scanln(&q)
	for k:=1;k<=q;k++{
		var n,k int
		fmt.Scanf("%d %d",&n,&k)

		var min,max int
		min=a[0]
		max=a[0]

		for i:=1;i<=n;i++{
			fmt.Scanf("%d",&a[i])
			if a[i]<min{
				min=a[i]
			}
			if a[i]>max{
				max=a[i]
			}

		}
		var ans2,ans3 int

		ans2=min+k;

		ans3=max-k

		if ans2>=ans3{
			fmt.Printf("%d\n",min+k)
		} else {
			fmt.Println("-1")
		}
	}

}


 package main

 import (
     "fmt"
     "math"
 )
 func main() {
     var nquery, n, k int64
     fmt.Scanf("%d", &nquery)
     for nquery > 0 {
         fmt.Scanf("%d %d\n", &n, &k)
         var min int64 = math.MaxInt64
         var max int64 = math.MinInt64
         var ai int64 = 0
         for n > 0 {
             if n > 1 {
                 fmt.Scanf("%d", &ai)
             } else {
                 fmt.Scanf("%d\n", &ai)
             }
             min = Min(ai, min)
             max = Max(ai, max)
             n--
         }
         if (max - min > k*2) {
             fmt.Println(-1)
         } else {
             fmt.Println(min + k)
         }

         nquery--
     }
 }

 func Min(x, y int64) int64 {
     if x < y {
         return x
     }
     return y
 }

 func Max(x, y int64) int64 {
     if x > y {
         return x
     }
     return y
 }


 package main

 import (
     "fmt"
     "math"
 )
 func main() {
     var nquery, n, k int
     fmt.Scanf("%d", &nquery)
     for nquery > 0 {
         fmt.Scanf("%d %d", &n, &k)
         min := math.MaxInt64
         max := math.MinInt64
         ai := 0
         for n > 0 {
             fmt.Scanf("%d", &ai)
             min = Min(ai, min)
             max = Max(ai, max)
             n--
         }
         if (max - min > k*2) {
             fmt.Println(-1)
         } else {
             fmt.Println(min + k)
         }

         nquery--
     }
 }

 func Min(x, y int) int {
     if x < y {
         return x
     }
     return y
 }

 func Max(x, y int) int {
     if x > y {
         return x
     }
     return y
 }


 package main

 import (
     "fmt"
     "math"
 )
 func main() {
     var nquery, n, k int64
     fmt.Scanf("%d\n", &nquery)
     for nquery > 0 {
         fmt.Scanf("%d %d\n", &n, &k)
         var min int64 = math.MaxInt64
         var max int64 = math.MinInt64
         var ai int64 = 0
         for n > 0 {
             if n > 1 {
                 fmt.Scanf("%d", &ai)
             } else {
                 fmt.Scanf("%d\n", &ai)
             }
             min = Min(ai, min)
             max = Max(ai, max)
             n--
         }
         if (max - min > k*2) {
             fmt.Println(-1)
         } else {
             fmt.Println(min + k)
         }

         nquery--
     }
 }

 func Min(x, y int64) int64 {
     if x < y {
         return x
     }
     return y
 }

 func Max(x, y int64) int64 {
     if x > y {
         return x
     }
     return y
 }


 package main

 import (
     "fmt"
     "math"
 )
 func main() {
     var nquery, n, k int64
     fmt.Scanf("%d", &nquery)
     for nquery > 0 {
         fmt.Scanf("%d %d\n", &n, &k)
         var min int64 = math.MaxInt64
         var max int64 = math.MinInt64
         var ai int64 = 0
         for n > 0 {
             fmt.Scanf("%d", &ai)
             min = Min(ai, min)
             max = Max(ai, max)
             n--
         }
         if (max - min > k*2) {
             fmt.Println(-1)
         } else {
             fmt.Println(min + k)
         }

         nquery--
     }
 }

 func Min(x, y int64) int64 {
     if x < y {
         return x
     }
     return y
 }

 func Max(x, y int64) int64 {
     if x > y {
         return x
     }
     return y
 }


 package main

 import (
     "fmt"
     "math"
 )
 func main() {
     var nquery, n, k int64
     fmt.Scanf("%d", &nquery)
     for nquery > 0 {
         fmt.Scanf("%d %d", &n, &k)
         var min int64 = math.MaxInt64
         var max int64 = math.MinInt64
         var ai int64 = 0
         for n > 0 {
             fmt.Scanf("%d", &ai)
             min = Min(ai, min)
             max = Max(ai, max)
             n--
         }
         if (max - min > k*2) {
             fmt.Println(-1)
         } else {
             fmt.Println(min + k)
         }

         nquery--
     }
 }

 func Min(x, y int64) int64 {
     if x < y {
         return x
     }
     return y
 }

 func Max(x, y int64) int64 {
     if x > y {
         return x
     }
     return y
 }


package main

import "fmt"

func main() {
	var requests int
	fmt.Scan(&requests)

	for i := 0; i < requests; i++ {
		var pieces int
		var k int
		min := 0
		max := 0
		fmt.Scan(&pieces)
		fmt.Scan(&k)
		var prices = make([]int, pieces)
		for j := 0; j < pieces; j++ {
			fmt.Scan(&prices[j])
			if j == 0 {
				min = prices[j]
				max = prices[j]
			}
			if prices[j] < min {
				min = prices[j]
			}
			if prices[j] > max {
				max = prices[j]
			}
		}
		if max > min + 2 * k {
			fmt.Println(-1)
		} else {
			fmt.Println(min + k)
		}

	}
}


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1183B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var t, n, k, v int
	for Fscan(in, &t); t > 0; t-- {
		mi, mx := int(1e9), 0
		for Fscan(in, &n, &k); n > 0; n-- {
			Fscan(in, &v)
			if v < mi {
				mi = v
			} else if v > mx {
				mx = v
			}
		}
		if mi+2*k >= mx {
			Fprintln(out, mi+k)
		} else {
			Fprintln(out, -1)
		}
	}
}

func main() { CF1183B(os.Stdin, os.Stdout) }


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1183B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var t, n, k, v int
	for Fscan(in, &t); t > 0; t-- {
		mi, mx := int(1e9), 0
		for Fscan(in, &n, &k); n > 0; n-- {
			Fscan(in, &v)
			if v < mi {
				mi = v
			}
			if v > mx {
				mx = v
			}
		}
		if mi+2*k >= mx {
			Fprintln(out, mi+k)
		} else {
			Fprintln(out, -1)
		}
	}
}

func main() { CF1183B(os.Stdin, os.Stdout) }


package main

import (
   "bufio"
   "fmt"
   "math"
   "os"
   "strconv"
   "sync"
)

const (
   MX_INT int64 = math.MaxInt64
   MN_INT int64 = math.MinInt64
)

func main() {
   for t := ScanInt64(); t > 0; t-- {
    n, k := ScanInt64(), ScanInt64()
    a := ScanInt64Slice(n)

    min := Mn(a...)
    max := Mx(a...)

    if max - min > 2*k {
      O <- S(-1)
    } else {
      O <- S(min + k)
    }

   }

   close(O)
   oWg.Wait()
}

func isValid(a []int64, k, B int64) bool {
  for i := 0; i < len(a); i++ {
    if abs(a[i] - k) > B {
      return false
    }
  }
  return true
}

func abs(x int64) int64 {
    if x < 0 {
        return -x
    }
    return x
}

/*********************** I/O ***********************/

var O chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var Pl func(a ...interface{}) (n int, err error)

func init() {
   Pl = fmt.Println

   in = bufio.NewScanner(os.Stdin)
   in.Buffer(make([]byte, 1024), int(1e8))
   in.Split(bufio.ScanWords)

   O = make(chan string, 16)
   oWg = &sync.WaitGroup{}
   oWg.Add(1)

   writer := bufio.NewWriterSize(os.Stdout, int(1e5))
   go func(writer *bufio.Writer) {
      defer oWg.Done()
      defer writer.Flush()

      for line := range O {
         writer.WriteString(line + "\n")
      }
   }(writer)
}

func ScanWord() string {
   in.Scan()
   return in.Text()
}

func ScanStringSlice(n int64) []string {
   length := int(n)
   s := make([]string, n)
   for i := 0; i < length; i++ {
      s[i] = ScanWord()
   }
   return s
}

func ScanInt64() int64 {
   intStr := ScanWord()
   i, err := strconv.ParseInt(intStr, 10, 64)
   if err != nil {
      panic(err)
   }
   return i
}

func ScanInt() int {
   intStr := ScanWord()
   i, err := strconv.Atoi(intStr)
   if err != nil {
      panic(err)
   }
   return i
}

func ScanInt64Slice(n int64) []int64 {
   length := int(n)
   arr := make([]int64, n)
   for i := 0; i < length; i++ {
      arr[i] = ScanInt64()
   }
   return arr
}

/*********************** Utils ***********************/

func Mx(args ...int64) int64 {
   maxVal := MN_INT
   for _, v := range args {
      if v > maxVal {
         maxVal = v
      }
   }
   return maxVal
}

func Mn(args ...int64) int64 {
   minVal := MX_INT
   for _, v := range args {
      if v < minVal {
         minVal = v
      }
   }
   return minVal
}

func LCM(a, b int64) int64 {
   return a / GCD(a, b) * b
}

func GCD(a, b int64) int64 {
   if (a == 0) {
      return b
   }
   return GCD(b%a, a)
}

func S(v interface{}) string {
   return fmt.Sprintf("%v", v)
}


#include<bits/stdc++.h>
#include<stdint.h>
#define int int_fast64_t
#pragma GCC optimize(2)
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> VI;
#define REP(i,j,k) for(register int (i)=(j);(i)<(k);++(i))
#define RREP(i,j,k) for(register int (i)=(j)-1;(i)>=(k);--(i))
#define ALL(a) (a).begin(),(a).end()
#define MST(a,v) memset((a),(v),sizeof(a))
#define pb push_back
#define F first
#define S second
#define endl '\n'
//																#define __debug
#ifdef __debug
	#define IOS (void)0
	#define de(...) cout<<__VA_ARGS__
	#define ar(a,s,t) {REP(__i,s,t)de((a)[__i]<<' ');de(endl);}
#else
	#define IOS cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(false)
	#define de(...) (void)0
	#define ar(...) (void)0
#endif

const int maxn=1e5+9;
const int limit=27;
int n,flag=0,a[maxn],vis[maxn]={};

inline int calc(int x){
	register int ret=0,cnt=0;
	++flag;
	REP(i,0,n)if(vis[a[i]]!=flag){
		if(!cnt)++ret,++flag;
		cnt=cnt+1,vis[a[i]]=flag;
		if(cnt>=x)cnt-=x;
	}
	return ret;
}

main(){
	IOS;
	cin>>n;
	REP(i,0,n)cin>>a[i];
	int x=n,k=1;
	while(x>=limit)cout<<(x=calc(k++))<<" ";
	RREP(i,limit,1){
		int l=k-1,r=n+1;
		while(l+1<r){
			int mid=l+r>>1;
			if(calc(mid)<i)r=mid;
			else l=mid;
		}
		if(l==k-1)continue;
		while(k<=l){
			cout<<i<<" ";
			++k;
		}
		//if(clock()*100>199*CLOCKS_PER_SEC)break;
	}
}


#include<bits/stdc++.h>
#include<stdint.h>
#define int int_fast64_t
#pragma GCC optimize(2)
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> VI;
#define REP(i,j,k) for(register int (i)=(j);(i)<(k);++(i))
#define RREP(i,j,k) for(register int (i)=(j)-1;(i)>=(k);--(i))
#define ALL(a) (a).begin(),(a).end()
#define MST(a,v) memset((a),(v),sizeof(a))
#define pb push_back
#define F first
#define S second
#define endl '\n'
//																#define __debug
#ifdef __debug
	#define IOS (void)0
	#define de(...) cout<<__VA_ARGS__
	#define ar(a,s,t) {REP(__i,s,t)de((a)[__i]<<' ');de(endl);}
#else
	#define IOS cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(false)
	#define de(...) (void)0
	#define ar(...) (void)0
#endif

const int maxn=1e5+9;
const int limit=28;
int n,flag=0,a[maxn],vis[maxn]={};

inline int calc(int x){
	register int ret=0,cnt=0;
	++flag;
	REP(i,0,n)if(vis[a[i]]!=flag){
		if(!cnt)++ret,++flag;
		cnt=cnt+1,vis[a[i]]=flag;
		if(cnt>=x)cnt-=x;
	}
	return ret;
}

main(){
	IOS;
	cin>>n;
	REP(i,0,n)cin>>a[i];
	int x=n,k=1;
	while(x>=limit)cout<<(x=calc(k++))<<" ";
	RREP(i,limit,1){
		int l=k-1,r=n+1;
		while(l+1<r){
			int mid=l+r>>1;
			if(calc(mid)<i)r=mid;
			else l=mid;
		}
		if(l==k-1)continue;
		while(k<=l){
			cout<<i<<" ";
			++k;
		}
		//if(clock()*100>199*CLOCKS_PER_SEC)break;
	}
}


#include<bits/stdc++.h>
#include<stdint.h>
#define int int_fast64_t
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> VI;
#define REP(i,j,k) for(register int (i)=(j);(i)<(k);++(i))
#define RREP(i,j,k) for(int (i)=(j)-1;(i)>=(k);--(i))
#define ALL(a) (a).begin(),(a).end()
#define MST(a,v) memset((a),(v),sizeof(a))
#define pb push_back
#define F first
#define S second
#define endl '\n'
//																#define __debug
#ifdef __debug
	#define IOS (void)0
	#define de(...) cout<<__VA_ARGS__
	#define ar(a,s,t) {REP(__i,s,t)de((a)[__i]<<' ');de(endl);}
#else
	#define IOS cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(false)
	#define de(...) (void)0
	#define ar(...) (void)0
#endif

const int maxn=1e5+9;
const int limit=78;
int n,flag=0,a[maxn],vis[maxn]={};

inline int calc(int x){
	int ret=0,cnt=0;
	++flag;
	REP(i,0,n)if(vis[a[i]]!=flag){
		if(!cnt)++ret,++flag;
		cnt=cnt+1,vis[a[i]]=flag;
		if(cnt>=x)cnt-=x;
	}
	return ret;
}

main(){
	IOS;
	cin>>n;
	REP(i,0,n)cin>>a[i];
	int x=n,k=1;
	while(x>=limit)cout<<(x=calc(k++))<<" ";
	RREP(i,limit,1){
		int l=k-1,r=n+1;
		while(l+1<r){
			int mid=l+r>>1;
			if(calc(mid)<i)r=mid;
			else l=mid;
		}
		if(l==k-1)continue;
		while(k<=l){
			cout<<i<<" ";
			++k;
		}
		//if(clock()*100>199*CLOCKS_PER_SEC)break;
	}
}


#include<bits/stdc++.h>
#include<stdint.h>
#define int int_fast64_t
#pragma GCC optimize(2)
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> VI;
#define REP(i,j,k) for(register int (i)=(j);(i)<(k);++(i))
#define RREP(i,j,k) for(register int (i)=(j)-1;(i)>=(k);--(i))
#define ALL(a) (a).begin(),(a).end()
#define MST(a,v) memset((a),(v),sizeof(a))
#define pb push_back
#define F first
#define S second
#define endl '\n'
//																#define __debug
#ifdef __debug
	#define IOS (void)0
	#define de(...) cout<<__VA_ARGS__
	#define ar(a,s,t) {REP(__i,s,t)de((a)[__i]<<' ');de(endl);}
#else
	#define IOS cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(false)
	#define de(...) (void)0
	#define ar(...) (void)0
#endif

const int maxn=1e5+9;
const int limit=40;
int n,flag=0,a[maxn],vis[maxn]={};

inline int calc(int x){
	register int ret=0,cnt=0;
	++flag;
	REP(i,0,n)if(vis[a[i]]!=flag){
		if(!cnt)++ret,++flag;
		cnt=cnt+1,vis[a[i]]=flag;
		if(cnt>=x)cnt-=x;
	}
	return ret;
}

main(){
	IOS;
	cin>>n;
	REP(i,0,n)cin>>a[i];
	int x=n,k=1;
	while(x>=limit)cout<<(x=calc(k++))<<" ";
	RREP(i,limit,1){
		int l=k-1,r=n+1;
		while(l+1<r){
			int mid=l+r>>1;
			if(calc(mid)<i)r=mid;
			else l=mid;
		}
		if(l==k-1)continue;
		while(k<=l){
			cout<<i<<" ";
			++k;
		}
		//if(clock()*100>199*CLOCKS_PER_SEC)break;
	}
}


#include<bits/stdc++.h>
#include<stdint.h>
#define int int_fast64_t
#pragma GCC optimize(2)
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> VI;
#define REP(i,j,k) for(register int (i)=(j);(i)<(k);++(i))
#define RREP(i,j,k) for(register int (i)=(j)-1;(i)>=(k);--(i))
#define ALL(a) (a).begin(),(a).end()
#define MST(a,v) memset((a),(v),sizeof(a))
#define pb push_back
#define F first
#define S second
#define endl '\n'
//																#define __debug
#ifdef __debug
	#define IOS (void)0
	#define de(...) cout<<__VA_ARGS__
	#define ar(a,s,t) {REP(__i,s,t)de((a)[__i]<<' ');de(endl);}
#else
	#define IOS cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(false)
	#define de(...) (void)0
	#define ar(...) (void)0
#endif

const int maxn=1e5+9;
const int limit=220;
int n,flag=0,a[maxn],vis[maxn]={};

inline int calc(int x){
	register int ret=0,cnt=0;
	++flag;
	REP(i,0,n)if(vis[a[i]]!=flag){
		if(!cnt)++ret,++flag;
		cnt=cnt+1,vis[a[i]]=flag;
		if(cnt>=x)cnt-=x;
	}
	return ret;
}

main(){
	IOS;
	cin>>n;
	REP(i,0,n)cin>>a[i];
	int x=n,k=1;
	while(x>=limit)cout<<(x=calc(k++))<<" ";
	RREP(i,limit,1){
		int l=k-1,r=n+1;
		while(l+1<r){
			int mid=l+r>>1;
			if(calc(mid)<i)r=mid;
			else l=mid;
		}
		if(l==k-1)continue;
		while(k<=l){
			cout<<i<<" ";
			++k;
		}
		//if(clock()*100>199*CLOCKS_PER_SEC)break;
	}
}


#include<bits/stdc++.h>
#include<stdint.h>
#define int int_fast64_t
#pragma GCC optimize(2)
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> VI;
#define REP(i,j,k) for(register int (i)=(j);(i)<(k);++(i))
#define RREP(i,j,k) for(register int (i)=(j)-1;(i)>=(k);--(i))
#define ALL(a) (a).begin(),(a).end()
#define MST(a,v) memset((a),(v),sizeof(a))
#define pb push_back
#define F first
#define S second
#define endl '\n'
//																#define __debug
#ifdef __debug
	#define IOS (void)0
	#define de(...) cout<<__VA_ARGS__
	#define ar(a,s,t) {REP(__i,s,t)de((a)[__i]<<' ');de(endl);}
#else
	#define IOS cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(false)
	#define de(...) (void)0
	#define ar(...) (void)0
#endif

const int maxn=1e5+9;
const int limit=30;
int n,flag=0,a[maxn],vis[maxn]={};

inline int calc(int x){
	register int ret=0,cnt=0;
	++flag;
	REP(i,0,n)if(vis[a[i]]!=flag){
		if(!cnt)++ret,++flag;
		cnt=cnt+1,vis[a[i]]=flag;
		if(cnt>=x)cnt-=x;
	}
	return ret;
}

main(){
	IOS;
	cin>>n;
	REP(i,0,n)cin>>a[i];
	int x=n,k=1;
	while(x>=limit)cout<<(x=calc(k++))<<" ";
	RREP(i,limit,1){
		int l=k-1,r=n+1;
		while(l+1<r){
			int mid=l+r>>1;
			if(calc(mid)<i)r=mid;
			else l=mid;
		}
		if(l==k-1)continue;
		while(k<=l){
			cout<<i<<" ";
			++k;
		}
		//if(clock()*100>199*CLOCKS_PER_SEC)break;
	}
}


#include<bits/stdc++.h>
#include<stdint.h>
#define int int_fast64_t
#pragma GCC optimize(2)
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> VI;
#define REP(i,j,k) for(register int (i)=(j);(i)<(k);++(i))
#define RREP(i,j,k) for(register int (i)=(j)-1;(i)>=(k);--(i))
#define ALL(a) (a).begin(),(a).end()
#define MST(a,v) memset((a),(v),sizeof(a))
#define pb push_back
#define F first
#define S second
#define endl '\n'
//																#define __debug
#ifdef __debug
	#define IOS (void)0
	#define de(...) cout<<__VA_ARGS__
	#define ar(a,s,t) {REP(__i,s,t)de((a)[__i]<<' ');de(endl);}
#else
	#define IOS cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(false)
	#define de(...) (void)0
	#define ar(...) (void)0
#endif

const int maxn=1e5+9;
const int limit=240;
int n,flag=0,a[maxn],vis[maxn]={};

inline int calc(int x){
	register int ret=0,cnt=0;
	++flag;
	REP(i,0,n)if(vis[a[i]]!=flag){
		if(!cnt)++ret,++flag;
		cnt=cnt+1,vis[a[i]]=flag;
		if(cnt>=x)cnt-=x;
	}
	return ret;
}

main(){
	IOS;
	cin>>n;
	REP(i,0,n)cin>>a[i];
	int x=n,k=1;
	while(x>=limit)cout<<(x=calc(k++))<<" ";
	RREP(i,limit,1){
		int l=k-1,r=n+1;
		while(l+1<r){
			int mid=l+r>>1;
			if(calc(mid)<i)r=mid;
			else l=mid;
		}
		if(l==k-1)continue;
		while(k<=l){
			cout<<i<<" ";
			++k;
		}
		//if(clock()*100>199*CLOCKS_PER_SEC)break;
	}
}


#include<bits/stdc++.h>
#include<stdint.h>
#define int int_fast64_t
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> VI;
#define REP(i,j,k) for(register int (i)=(j);(i)<(k);++(i))
#define RREP(i,j,k) for(int (i)=(j)-1;(i)>=(k);--(i))
#define ALL(a) (a).begin(),(a).end()
#define MST(a,v) memset((a),(v),sizeof(a))
#define pb push_back
#define F first
#define S second
#define endl '\n'
//																#define __debug
#ifdef __debug
	#define IOS (void)0
	#define de(...) cout<<__VA_ARGS__
	#define ar(a,s,t) {REP(__i,s,t)de((a)[__i]<<' ');de(endl);}
#else
	#define IOS cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(false)
	#define de(...) (void)0
	#define ar(...) (void)0
#endif

const int maxn=1e5+9;
const int limit=60;
int n,a[maxn],vis[maxn];

inline int calc(int x){
	int ret=0,cnt=0,flag=1;
	MST(vis,0);
	REP(i,0,n)if(vis[a[i]]!=flag){
		if(!cnt)++ret,++flag;
		cnt=(cnt+1)%x,vis[a[i]]=flag;
	}
	return ret;
}

main(){
	IOS;
	cin>>n;
	REP(i,0,n)cin>>a[i],--a[i];
	int x=n,k=1;
	while(x>=limit&&k<n)cout<<(x=calc(k++))<<" ";
	RREP(i,limit,1){
		int l=k,r=n+1;
		while(l+1<r){
			int mid=(l+r)/2;
			if(calc(mid)<i)r=mid;
			else l=mid;
		}
		if(calc(l)<i)continue;
		while(k<=l){
			cout<<i<<" ";
			++k;
		}
		if(clock()*100>199*CLOCKS_PER_SEC)break;
	}
}


#include<bits/stdc++.h>
#include<stdint.h>
#define int int_fast64_t
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> VI;
#define REP(i,j,k) for(register int (i)=(j);(i)<(k);++(i))
#define RREP(i,j,k) for(int (i)=(j)-1;(i)>=(k);--(i))
#define ALL(a) (a).begin(),(a).end()
#define MST(a,v) memset((a),(v),sizeof(a))
#define pb push_back
#define F first
#define S second
#define endl '\n'
//																#define __debug
#ifdef __debug
	#define IOS (void)0
	#define de(...) cout<<__VA_ARGS__
	#define ar(a,s,t) {REP(__i,s,t)de((a)[__i]<<' ');de(endl);}
#else
	#define IOS cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(false)
	#define de(...) (void)0
	#define ar(...) (void)0
#endif

const int maxn=1e5+9;
const int limit=100;
int n,a[maxn],vis[maxn];

inline int calc(int x){
	int ret=0,cnt=0,flag=1;
	MST(vis,0);
	REP(i,0,n)if(vis[a[i]]!=flag){
		if(!cnt)++ret,++flag;
		cnt=(cnt+1)%x,vis[a[i]]=flag;
	}
	return ret;
}

main(){
	IOS;
	cin>>n;
	REP(i,0,n)cin>>a[i],--a[i];
	int x=n,k=1;
	while(x>=limit&&k<n)cout<<(x=calc(k++))<<" ";
	RREP(i,limit,1){
		int l=k,r=n+1;
		while(l+1<r){
			int mid=(l+r)/2;
			if(calc(mid)<i)r=mid;
			else l=mid;
		}
		if(calc(l)<i)continue;
		while(k<=l){
			cout<<i<<" ";
			++k;
		}
		if(clock()*10>19*CLOCKS_PER_SEC)break;
	}
}


#include<bits/stdc++.h>
#include<stdint.h>
#define int int_fast64_t
#pragma GCC optimize(2)
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> VI;
#define REP(i,j,k) for(register int (i)=(j);(i)<(k);++(i))
#define RREP(i,j,k) for(register int (i)=(j)-1;(i)>=(k);--(i))
#define ALL(a) (a).begin(),(a).end()
#define MST(a,v) memset((a),(v),sizeof(a))
#define pb push_back
#define F first
#define S second
#define endl '\n'
//																#define __debug
#ifdef __debug
	#define IOS (void)0
	#define de(...) cout<<__VA_ARGS__
	#define ar(a,s,t) {REP(__i,s,t)de((a)[__i]<<' ');de(endl);}
#else
	#define IOS cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(false)
	#define de(...) (void)0
	#define ar(...) (void)0
#endif

const int maxn=1e5+9;
const int limit=270;
int n,flag=0,a[maxn],vis[maxn]={};

inline int calc(int x){
	register int ret=0,cnt=0;
	++flag;
	REP(i,0,n)if(vis[a[i]]!=flag){
		if(!cnt)++ret,++flag;
		cnt=cnt+1,vis[a[i]]=flag;
		if(cnt>=x)cnt-=x;
	}
	return ret;
}

main(){
	IOS;
	cin>>n;
	REP(i,0,n)cin>>a[i];
	int x=n,k=1;
	while(x>=limit)cout<<(x=calc(k++))<<" ";
	RREP(i,limit,1){
		int l=k-1,r=n+1;
		while(l+1<r){
			int mid=l+r>>1;
			if(calc(mid)<i)r=mid;
			else l=mid;
		}
		if(l==k-1)continue;
		while(k<=l){
			cout<<i<<" ";
			++k;
		}
		//if(clock()*100>199*CLOCKS_PER_SEC)break;
	}
}