The maximum number of trains that platform k can support

Given the arrival and departure times from the N trains that reach the train station for this platform k, return the maximum number of trains that we can place on the platforms k.

k <<< N

Arrival and departure times Array

Input:  arr[]  = {9:00,  9:40, 9:50,  11:00, 15:00, 18:00}
        dep[]  = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00}

In some interview this question was asked to me, so why is this the best algorithm? This question is slightly modified from this question.

http://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/

I tried the greedy algorithm for this question, but it does not work for all test cases.

+4
source share
3 answers

( ), :

  • .

  • lastDeparture k, lastDeparture[i] - , i ( ).

  • :

    • , lastDeparture[i] <= currentTrain.arrival.

    • , .

    • , lastDeparture ( , ).

    • (.. lastDeparture[i] = currentTrain.departure.

:

, . , , . - . . , .

: O(n log n) ( 3 , , ).

+1

, . , , , .

:

  • ( , /).
  • , .
  • k, , , "" . NB: .
  • - .

, , , , . , , , , .

O (N * K) , . , .

- O (N * K).

+1

, , , stack k, . ( ):

while current.ArrivalTime > stack.Last.DepartureTime:
  remove the top element (train) from the stack
push the current train IF there is room, else ignore it
answer = max(answer, stack.Size)

The maximum size that your stack reaches will be the answer to the problem.

This should be O(n log n)due to sorting, since each train enters / leaves the stack no more than once.

-1
source

All Articles