The problem is as follows: "Given arrival and departure times of all trains that reach a railway station, the task is to find the minimum number of platforms required for the railway station so that no train waits. Trains can arrive before midnight and arrive after midnight"
I understand how the traditional problem works without the condition that trains can arrive before midnight and leave after midnight, as many of the solutions I've seen for this problem doesn't take the midnight condition into account.
My approach was to just use the traditional "Brute Force" method however I considered the trains which arrived before midnight and left after midnight special cases called "Crossover". I've written the following code (in Python), but I'm not entirely certain whether it is the correct approach. For the selected input the code works correctly, but is there any better/more clearer way to approach this problem without using Brute Force?
def findPlatform(arr, dep, n):
# Crossover means a train arrives before midnight and leaves after midnight
i = 0
platmax = 1
while i < n:
platforms = 1
j = i+1
while j < n:
# Crossover
if arr[i] > dep[i]:
# Crossover
if ((arr[i] <= arr[j] and arr[i] >= dep[j]) or (arr[j] <= arr[i] and arr[j] >= dep[i])):
if arr[j] > dep[i]:
platforms += 1
# Not Crossover
else:
if ((arr[i] <= arr[j] and arr[i] >= dep[j]) or (arr[j] <= arr[i] and arr[j] >= dep[i])):
platforms += 1
# Not Crossover
else:
# Crossover
if arr[j] > dep[j]:
if ((arr[i] >= arr[j] and arr[i] >= dep[j]) or (arr[j] >= arr[i] and arr[j] <= dep[i])):
platforms += 1
# Not Crossover
else:
if ((arr[i] >= arr[j] and arr[i] <= dep[j]) or (arr[j] >= arr[i] and arr[j] <= dep[i])):
platforms += 1
j += 1
if platforms > platmax:
platmax = platforms
i += 1
return platmax
# driver code
#arr = [900, 940, 950, 1100, 1500, 1800];
#dep = [910, 1120, 1130, 1200, 1900, 2000];
arr = [200, 240, 300, 420, 430, 455, 950, 1130, 2300, 2330, 2340, 2350]
dep = [300, 400, 450, 500, 530, 540, 1150, 1155, 10, 100, 110, 250]
n = len(arr)
print("Minimum Number of Platforms Required = ",
findPlatform(arr, dep, n))