714069. Minimum Platforms 2
Minimum Platforms 2
Summary
The Minimum Platforms 2 problem involves scheduling trains on a single track railway with limited platforms. The goal is to find the minimum number of platforms needed such that no train has to wait for another to leave the platform. This problem requires understanding of dynamic programming and its application in optimizing solutions.
Detailed Explanation
To solve this problem, we can start by initializing an array dp where dp[i] represents the maximum number of trains on the track up to the ith minute. The key idea is to keep track of the maximum number of trains that have arrived at or before each minute and ensure that no train has to wait for another to leave.
Let's break down the solution:
- Initialize
dp[0]as 1, since only one train can be on the track initially. - Iterate over all minutes from 1 to
max_time, wheremax_timeis the total time in minutes. - For each minute
i, calculate the maximum number of trains that have arrived at or before this minute. - Add the number of trains arriving at minute
itodp[i-1]. This ensures that we include all trains that arrive at or before this minute and update our count accordingly. - Update
dp[i]as the maximum value betweendp[i-1]and the new count calculated in step 4. This ensures that we always keep track of the maximum number of trains on the track up to each minute.
The time complexity for this solution is O(max_time), where max_time is the total time in minutes, as we need to iterate over all minutes. The space complexity is O(max_time) as well, since we store the count of trains at each minute.
+-----------+
| 1 |
| dp[0] = 1|
+-----------+
+-----------+
| 1 | 2 | 3 | ... | max_time |
| dp[1] = 2 | dp[2] = 3 | ... | dp[max_time-1] = ? |
+-----------+
dp[i] = maximum of:
dp[i-1] (previous minute's trains)
new count = number of trains arriving at minute i
Optimized Solutions
Java
public int minPlatforms(int[] arrival, int[] departure) {
int n = arrival.length;
int max_time = 0;
for (int time : arrival) {
max_time = Math.max(max_time, time);
}
for (int time : departure) {
max_time = Math.max(max_time, time);
}
int[] dp = new int[max_time + 1];
dp[0] = 1;
for (int i = 1; i <= max_time; i++) {
int prev_trains = dp[i - 1];
int arriving_trains = 0;
for (int j = 0; j < n; j++) {
if (arrival[j] <= i && departure[j] >= i) {
arriving_trains++;
}
}
dp[i] = Math.max(dp[i - 1], prev_trains + arriving_trains);
}
return dp[max_time];
}