#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MOD = 1e9 + 7;
void solve(){
int n;
cin >> n;
vector<pair<int, int>> a(n);
for(int i = 0; i < n; i++){
cin >> a[i].first;
a[i].second = i;
}
if(n == 1){
cout << 0 << "\n";
return;
}
sort(a.begin(), a.end());
int s = a[0].first + 1, e = a[n - 1].first;
int ans = a[n - 1].first - a[0].first;
while(s <= e){
ll mid = s + (e - s) / 2;
set<pair<int, int>> p, q;
vector<int> b(n);
for(int i = 0; i < n; i++){
if(a[i].first < mid){
p.insert({a[i].second, mid - a[i].first});
b[a[i].second] = a[i].first;
}else if(a[i].first > mid){
int extra = a[i].first - mid;
q.insert({-a[i].second, extra});
b[a[i].second] = mid;
}else{
b[a[i].second] = a[i].first;
}
}
while(p.size() && q.size()){
auto [g, h] = *(q.begin());
g = -g;
auto [l, r] = *(p.begin());
if(g > l){
q.erase(q.find({-g, h}));
}else{
if(h >= r){
p.erase(p.find({l, r}));
q.erase(q.find({-g, h}));
b[l] += r;
h -= r;
if(h > 0)q.insert({-g, h});
}else{
p.erase(p.find({l, r}));
q.erase(q.find({-g, h}));
b[l] += h;
r -= h;
p.insert({l, r});
}
}
}
for(auto [x, y]: q){
b[-x] += y;
}
sort(b.begin(), b.end());
if(mid == 2){
for(auto x: b){
cout << x << " ";
}
cout << "\n";
}
if(b[0] >= mid){
ans = min(ans, b[n - 1] - b[0]);
s = mid + 1;
}else{
e = mid - 1;
}
}
cout << ans << "\n";
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
cin >> t;
for(int i = 1; i <= t; i++){
solve();
}
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CiNkZWZpbmUgbGwgbG9uZyBsb25nCgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY29uc3QgaW50IE1PRCA9IDFlOSArIDc7Cgp2b2lkIHNvbHZlKCl7CglpbnQgbjsKCWNpbiA+PiBuOwoJCgl2ZWN0b3I8cGFpcjxp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