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:
- Initialize an array
dpof sizen, wherenis the number of trains. - 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.
- 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
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;
}