Given an array of N elements, select P independent pairs out of them such that the max of instability for the selected pair is minimised.
Instability is absolute of difference of elements within the pair.
int solve(int n,int p,vector<int> a)
{
sort(a.begin(),a.end());
int lo=0,hi=2e9+5,ans=-1; // assuming range of ai is 1e9
while(hi >= lo)
{
int mid=(lo+hi)/2;
vector<int> arr(n);
for(int i = 1;i < n;i++)
{
if(a[i]-a[i-1]<=mid)
{
arr[i-1]=1;
arr[i]=1;
}
}
int numPairs=0;
for(int i = 0;i < n;i++)
{
if(arr[i]==0)
continue;
int j=i;
while(j < n && arr[j]==1)
j++;
int cnt=j-i;
numPairs+=cnt/2;
i=j;
}
if(numPairs < p)
lo=mid+1;
else
ans=mid,hi=mid-1;
}
return ans;
}
Time Complexity : O(N*log(1e9))
If it is possible to select P pairs with max instability k then it is definitely possible to select P pairs with instability greater than k . Hence we can do binary search on k which will range from 0 to max(A)-min(A) and for each value of k we can greedily check on the sorted array whether it is possible to select P pairs or not . Overall time complexity would be O(nlogn)
it seems test case is not handled properly. answer must be 3 only.
The following problem has been updated based on the user challenge raised by Rohit.
Do reach out to us using the challenge button incase you find any other issues !
Happy Coding !
.