714069. Minimum Platforms 2

Medium

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:

  1. Initialize dp[0] as 1, since only one train can be on the track initially.
  2. Iterate over all minutes from 1 to max_time, where max_time is the total time in minutes.
  3. For each minute i, calculate the maximum number of trains that have arrived at or before this minute.
  4. Add the number of trains arriving at minute i to dp[i-1]. This ensures that we include all trains that arrive at or before this minute and update our count accordingly.
  5. Update dp[i] as the maximum value between dp[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

View on GeeksforGeeks
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];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.