int[] arrival = {900, 940, 950, 1100, 1500, 1800}; int[] departure = {910, 1200, 1120, 1130, 1900, 2000}; int FindPlatforms(int[] arr, int[] dep) { Array.Sort(arr); Array.Sort(dep); int platform_needed = 1, result = 1; int i = 1, j = 0; while (i < arr.Length && j < dep.Length) { if (arr[i] <= dep[j]) { platform_needed++; i++; if (platform_needed > result) result = platform_needed; } else { platform_needed--; j++; } } return result; } int answer = FindPlatforms(arrival, departure); Console.WriteLine(answer);
The code sorts arrival and departure times. It then uses two pointers to count how many trains are at the station at the same time. The maximum count is the minimum number of platforms needed.
Here, the maximum overlap is 3 trains at once, so 3 platforms are needed.
'platform_needed' increases when a train arrives before the earliest departure and decreases when a train departs. So it tracks how many trains are currently at the station simultaneously.
int[] arrival = {900, 940, 950}; int[] departure = {910, 920}; int FindPlatforms(int[] arr, int[] dep) { Array.Sort(arr); Array.Sort(dep); int platform_needed = 1, result = 1; int i = 1, j = 0; while (i < arr.Length) { if (arr[i] <= dep[j]) { platform_needed++; i++; if (platform_needed > result) result = platform_needed; } else { platform_needed--; j++; } } return result; } int answer = FindPlatforms(arrival, departure); Console.WriteLine(answer);
The departure array has fewer elements than the arrival array. The code assumes both arrays have the same length, so accessing dep[2] causes an IndexOutOfRangeException.
int[] arrival = {1000, 1010, 1025, 1030, 1040}; int[] departure = {1020, 1035, 1045, 1050, 1100}; int FindPlatforms(int[] arr, int[] dep) { Array.Sort(arr); Array.Sort(dep); int platform_needed = 1, result = 1; int i = 1, j = 0; while (i < arr.Length && j < dep.Length) { if (arr[i] <= dep[j]) { platform_needed++; i++; if (platform_needed > result) result = platform_needed; } else { platform_needed--; j++; } } return result; } int answer = FindPlatforms(arrival, departure); Console.WriteLine(answer);
The maximum number of trains at the station simultaneously is 3, so 3 platforms are needed.
Sorting separately allows the algorithm to process the earliest arrival or departure next, simulating the timeline of trains arriving and leaving. This helps count how many trains are at the station simultaneously.
