We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I tried the below solution which seemed to pass all the test cases. This solution sorts the input array and has a time complexity of O(nlog(n)). The algorithm used is somewhat related to the two-pointer algorithm.
static int flatlandSpaceStations(int n, int[] c) {
if(c.length == n)
return 0;
int maxDist = Integer.MIN_VALUE;
if(c.length == 1){
for(int i=0; i < n; i++){
maxDist = Math.max(calculateDistance(i, c[0]), maxDist);
}
}else{
int left = 0;
int right = 1;
int leftDist = 0;
int rightDist = 0;
Arrays.sort(c);
for(int i=0; i < n; i++){
leftDist = calculateDistance(i, c[left]);
rightDist = calculateDistance(i, c[right]);
if(leftDist > rightDist){
maxDist = Math.max(rightDist, maxDist);
if(right < c.length -1){
left++;
right++;
}
}else{
maxDist = Math.max(leftDist, maxDist);
}
}
}
return maxDist;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Flatland Space Stations
You are viewing a single comment's thread. Return to all comments →
I tried the below solution which seemed to pass all the test cases. This solution sorts the input array and has a time complexity of O(nlog(n)). The algorithm used is somewhat related to the two-pointer algorithm.
static int flatlandSpaceStations(int n, int[] c) {