710136. Maximum trains for which stoppage can be provided

Medium

Maximum trains for which stoppage can be provided

Summary

The problem is to find the maximum number of trains that can be stopped at a station where the stopping time is given. The stopping times are in non-decreasing order, and we need to determine how many trains can be stopped based on the available time.

Detailed Explanation

To solve this problem, we will use dynamic programming. We create an array dp of size n, where n is the number of trains. Initially, all values are set to 0. Then, for each train, we check if it can be stopped based on the available time. If it can, we increment the count in dp.

Here's a step-by-step breakdown:

  1. Initialize an array dp of size n, where n is the number of trains.
  2. Iterate over each train:
    • For each train, calculate the stopping time.
    • Check if the stopping time is less than or equal to the current available time.
    • If it can be stopped, increment the count in dp.
  3. Return the maximum value in dp.

Here's an ASCII art diagram illustrating this process:

          +-----+
          | Train1 |
          +-----+
                  |
                  v
+---------------+
| Available Time |
+---------------+

Time complexity: O(n) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int maximumTrains(int[] stoppingTimes) {
    int n = stoppingTimes.length;
    int maxTrains = 0;
    int availableTime = 0;

    for (int i = 0; i < n; i++) {
        if (stoppingTimes[i] <= availableTime) {
            availableTime += stoppingTimes[i];
            maxTrains++;
        }
    }

    return maxTrains;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.