Find maximum distance between any city and station | Java program to calculate the maximum distance between any city and its nearest station ; Function to calculate the maximum distance between any city and its nearest station ; Initialize boolean list ; Assign True to cities containing station ; Driver code
import java . util . * ; class GFG { static int findMaxDistance ( int numOfCities , int station [ ] , int n ) { boolean hasStation [ ] = new boolean [ numOfCities + 1 ] ; 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 ) ; } 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 ) ) ; } }