Find maximum distance between any city and station in Python


Suppose we have N number of cities, and they are numbered from 0 to N-1 and we also have the cities in which stations are located, we have to find the maximum distance between any city and its nearest station. We have to keep in mind that the cities with stations can be given in any order.

So, if the input is like N = 6 and stations = [2,4], then the output will be 2

To solve this, we will follow these steps −

  • station_present := a list of size N, and fill with False

  • for each city in station, do

    • station_present[city] := True

  • dist := 0, maximum_dist := minimum of station

  • for city in range 0 to N, do

    • if station_present[city] is True, then

      • maximum_dist := maximum of(dist + 1) / 2, maximum_dist

      • dist := 0

    • otherwise,

      • dist := dist + 1

  • return maximum of maximum_dist, dist

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def get_max_dist(N, station):
   station_present = [False] * N
   for city in station:
      station_present[city] = True
   dist, maximum_dist = 0, min(station)
   for city in range(N):
      if station_present[city] == True:
         maximum_dist = max((dist + 1) // 2, maximum_dist)
         dist = 0
      else:
         dist += 1
   return max(maximum_dist, dist)
N = 6
station = [2, 4]
print(get_max_dist(N, station))

Input

6, [2,4]

Output

2

Updated on: 25-Aug-2020

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements