Minimum number of platforms required for a railway
unknown
java
10 months ago
1.2 kB
6
Indexable
import java.util.*;
class Solution {
// Function to find the minimum number of platforms required at the
// railway station such that no train waits.
static int findPlatform(int arr[], int dep[]) {
int n = arr.length;
// Sort arrival and departure arrays
Arrays.sort(arr);
Arrays.sort(dep);
// Pointers for arrival and departure times
int i = 1, j = 0;
// Count of platforms required at the station at a time
int platforms = 1, result = 1;
while (i < n && j < n) {
// If the next event is an arrival
if (arr[i] <= dep[j]) {
platforms++; // Need one more platform
i++; // Move to the next arrival
}
// If the next event is a departure
else {
platforms--; // One platform becomes free
j++; // Move to the next departure
}
// Update the result to store the maximum number of platforms required
result = Math.max(result, platforms);
}
return result; // Return the maximum platforms needed
}
}
Editor is loading...
Leave a Comment