1. Pairwise Overlap Counting
Intuition
For each train, iterate through all other trains and count how many overlap with its time window. Take the maximum count.
Algorithm
- Step 1: Initialize maxPlatforms = 0.
- Step 2: For each train i from 0 to N - 1:
- Step 3: Initialize count = 1.
- Step 4: For every other train j from 0 to N - 1 (j != i): check if train j overlaps with train i.
- Step 5: If overlapping, increment count.
- Step 6: Update maxPlatforms = max(maxPlatforms, count), and return.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution {public: int findPlatform(int arr[], int dep[], int n) { int maxPlatforms = 1; for (int i = 0; i < n; ++i) { int count = 1; for (int j = 0; j < n; ++j) { if (i != j) { // Train j is at the station during train i's arrival if (arr[i] >= arr[j] && arr[i] <= dep[j]) { count++; } } } maxPlatforms = max(maxPlatforms, count); } return maxPlatforms; }}; int main() { Solution sol; int arr[] = {900, 940, 950, 1100, 1500, 1800}; int dep[] = {910, 1200, 1120, 1130, 1900, 2000}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Platforms: " << sol.findPlatform(arr, dep, n) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2) - Space complexity:
O(1)