#include<map>
#include<set>
#include<cmath>
#include<deque>
#include<queue>
#include<stack>
#include<string>
#include<bitset>
#include<cstdio>
#include<vector>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>
#include<unordered_map>
//#include<bits/stdc++.h>
#define fi first
#define se second
#define eps 1e-8
#define ll long long
#define ull unsigned long long
#define pb push_back
#define inf 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f3f3f
#define P pair<ll, ll>
#define pi acos(-1)
#define lson l,mid,rt*2
#define rson mid+1,r,rt*2+1
#define lowbit(x) (x&(-x))
#define SZ(x) ((ll)(x).size())
#define met(a,x) memset(a,x,sizeof(a))
#define openin(x) freopen(x, "r", stdin)
#define openout(x) freopen(x, "w",stdout)
#define rep(i,a,b) for(int i = a;i <= b;i++)
#define bep(i,a,b) for(int i = a;i >= b;i--)
#define ios() ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
ll mod = 998244353;
ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }
ll lcm(ll a, ll b) { return a * b / gcd(a, b); }
int days[15] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int is_leapyear(int y) { return y % 400 == 0 || (y % 4 == 0 && y % 100 != 0); }
int dx[8] = { 0,0,1,-1,-1,-1,1,1 };
int dy[8] = { 1,-1,0,0,-1,1,-1,1 };
inline ll read() {
    ll x = 0, sign = 1; char ch = getchar();
    for (; !isdigit(ch); ch = getchar()) if (ch == '-') sign = -1;
    for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0';
    return sign * x;
}
inline void write(ll x) {
    char r[30];
    int t = 0;
    if (x < 0) {
        x = -x;
        putchar('-');
    }
    do {
        r[t++] = x % 10 + '0';
        x /= 10;
    } while (x);
    while (t)putchar(r[--t]);
}
inline void writesp(ll x) { write(x); putchar(' '); }
inline void writeln(ll x) { write(x); putchar('\n'); }
ll qpow(ll a, ll b) {
    ll ans = 1;
    while (b) {
        if (b & 1)ans = ans * a % mod;
        a = a * a % mod;
        b >>= 1;
    }
    return ans;
}
const int N = 300010;
int a[N],vis[N];
int f[N];
int main() {
    int T;cin >> T;
    while(T--){
        int n;cin >> n;
        rep(i,1,n)vis[i] = f[i] = 0;
        int mx = 0;
        int k = 0;
        rep(i,1,n){
            cin >> a[i];
            vis[a[i]]++;
            if(i > 1 && a[i] == a[i-1])f[a[i]] += 2,k++;
            mx = max(mx,vis[a[i]]);
        }
        f[a[1]]++;f[a[n]]++;
        a[n+1] = a[1];
        int tot = 0;
        rep(i,1,n){
            if(a[i] == a[i+1]){
                tot++;
            }
        }
        if(mx > n - mx + 1)cout << -1 << endl;
        else{
            cout << k + max(0,*max_element(f+1,f+1+n) - k - 2) << endl;
        }
    }
    return 0;
}
