#include<iostream>
using namespace std;
int sum_of_array(int A[], int N);
void mover(int A[], int i, int j);
int run_through(int A[], int N, int D);
bool all_equal(int A[], int N);
bool possible(int A[], int N, int D);
void smaller(int A[], int i, int mean, int D, int &x, int N);
void bigger(int A[], int i, int mean, int D, int &x, int N);
int main()
{
const int SIZE = 100005;
int T, N, D, A[SIZE], X[12];
cin>>T;
for(int i=0; i<T; ++i)
{
cin>>N;
cin>>D;
for(int j=0; j<N; ++j) cin>>A[j];
if(!possible(A, N, D)) X[i] = -1;
else if(all_equal(A, N)) X[i] = 0;
else X[i] = run_through(A, N, D);
}
for(int i=0; i<T; ++i) cout<<X[i]<<"\n";
return 0;
}
int sum_of_array(int A[], int N)
{
int sum = A[0];
for(int i=1; i<N; ++i) sum+=A[i];
cout << "sum = " << sum << endl;
return sum;
}
void mover(int A[], int i, int j)
{
A[i]--;
A[j]++;
}
int run_through(int A[], int N, int D)
{
int x = 0;
int mean = sum_of_array(A, N)/N;
for(int i=0; i<N; ++i)
{
cout << "A[" << i << "] = " << A[i] << endl;
if(A[i]>mean && i+D<N) bigger(A, i, mean, D, x, N);
else if(A[i]<mean && i+D<N) smaller(A, i, mean, D, x, N);
}
if(x==0 || !all_equal(A, N)) return -1;
else return x;
}
bool all_equal(int A[], int N)
{
for(int i=1; i<N; ++i) if(A[0]!=A[i]) return false;
return true;
}
bool possible(int A[], int N, int D)
{
if(sum_of_array(A, N)%N!=0) return false;
if(!all_equal(A, N) && (D==0 || D>N-1)) return false;
return true;
}
void smaller(int A[], int i, int mean, int D, int &x, int N)
{
int j=i+D;
while(A[i]<mean && j<N)
{
if(A[j]>0)
{
mover(A, j, i);
x+=(j-i)/D;
}
else j+=D;
}
}
void bigger(int A[], int i, int mean, int D, int &x, int N)
{
while(A[i]>mean)
{
mover(A, i, i+D);
x++;
}
}
I2luY2x1ZGU8aW9zdHJlYW0+Cgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKaW50IHN1bV9vZl9hcnJheShpbnQgQVtdLC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