Code
// Java program to calculate the maximum
// distance between any city
// and its nearest station
import java.util.*;
class GFG
{
// Function to calculate the maximum
// distance between any city and its nearest station
static int findMaxDistance(int numOfCities,
int station[],int n)
{
// Initialize boolean list
boolean hasStation[] = new boolean[numOfCities + 1];
// Assign True to cities containing station
for (int city = 0; city < n; city++)
{
hasStation[station[city]] = true;
}
int dist = 0;
int maxDist = Integer.MAX_VALUE;
for(int i = 0; i < n; i++)
{
maxDist = Math.min(station[i],maxDist);
}
for (int city = 0; city < numOfCities; city++)
{
if (hasStation[city] == true)
{
maxDist = Math.max((dist + 1) / 2, maxDist);
dist = 0;
}
else
dist += 1;
}
return Math.max(maxDist, dist);
}
//Driver code
public static void main(String args[])
{
int numOfCities = 6;
int station[] = {3, 1};
int n = station.length;
System.out.println("Max Distance:"+
findMaxDistance(numOfCities,station, n));
}
}
Log in or sign up for Devpost to join the conversation.