#include <iostream>
#include <algorithm>
#define MAX_LENGTH 100000
using namespace std;
void readstr(long int a[], long int N) {
long int i = 0;
while (i < N) {
cin >> a[i++];
};
//for (long i=0; i < N; i++) {
// cout << a[i] << endl;
//}
}
long int aggcow(long int a[], long int N, long int C) {
sort(a,a+N);
long int i, spacing=0, mid, last, low, high;
bool complain;
long int minspc=1;
long int maxspc=a[N-1]-a[0]+1;
while ( minspc<maxspc ) {
spacing=minspc+(maxspc-minspc)/2;
//cout << "Spacing: " << spacing << endl;
for (i=1, low=1, last=0,complain=false; i<C && complain==false; ) {
//cout << "i: " << i << endl;
high=N-1;
while (low < high) {
mid=low+(high-low)/2;
//cout << "i="<< i << " last="<< a[last] <<" low="<< a[low] << " mid="<< a[mid] << " high="<< a[high] << endl;
if (a[mid]-a[last]>=spacing) {
high=mid;
}
else {
low=mid+1;
}
}
//cout << "distance from last: " << a[low] - a[last] << endl;
if ( a[low] - a[last] < spacing ) {
//cout << a[low] << endl;
complain=true;
//cout << "Breaking" << endl;
}
else {
//cout << "Chose : " << a[low] << endl << endl;
last=low;
low=last+1;
i++;
}
}
if (complain==true) { // Could not find subset with minimum adjacent distance
//cout << "Could Not Found\n\n";
maxspc=spacing;
}
else { // Found the subset
minspc=spacing+1;
//cout << "Found\n\n";
}
}
return minspc-1;
}
int main ()
{
long int T, N, C, a[MAX_LENGTH];
cin >> T;
while (T--) {
cin >> N;
cin >> C;
readstr(a,N);
cout << aggcow(a,N,C) << endl;
}
//cout << C << endl;
//cout << N << C;
//for (long int i=0; i < N; i++) { cout << a[i] << endl; }
return 0;
}
I am using binary search and also getting correct output on the testcases provided in the comments.. Someone please help me find out where I am going wrong