package main import ( "fmt" "sort" ) func minPlatforms(arrivals []int, departures []int) int { sort.Ints(arrivals) sort.Ints(departures) platformsNeeded := 0 maxPlatforms := 0 i, j := 0, 0 for i < len(arrivals) && j < len(departures) { if arrivals[i] <= departures[j] { platformsNeeded++ if platformsNeeded > maxPlatforms { maxPlatforms = platformsNeeded } i++ } else { platformsNeeded-- j++ } } return maxPlatforms } func main() { arrivals := []int{900, 940, 950, 1100, 1500, 1800} departures := []int{910, 1200, 1120, 1130, 1900, 2000} fmt.Println(minPlatforms(arrivals, departures)) }
The code sorts arrival and departure times. It then uses two pointers to count how many trains are at the station simultaneously. The maximum count during this process is the minimum number of platforms needed.
For the given times, the maximum overlap is 3 trains at once.
The minimum number of platforms depends on the maximum number of trains that are at the station simultaneously. This ensures no train waits for a platform.
package main import ( "fmt" "sort" ) func minPlatforms(arrivals []int, departures []int) int { sort.Ints(arrivals) sort.Ints(departures) platformsNeeded := 0 maxPlatforms := 0 i, j := 0, 0 for i < len(arrivals) || j < len(departures) { if arrivals[i] <= departures[j] { platformsNeeded++ if platformsNeeded > maxPlatforms { maxPlatforms = platformsNeeded } i++ } else { platformsNeeded-- j++ } } return maxPlatforms } func main() { arrivals := []int{900, 940, 950, 1100, 1500, 1800} departures := []int{910, 1200, 1120, 1130, 1900, 2000} fmt.Println(minPlatforms(arrivals, departures)) }
The loop condition uses OR (||) which allows i or j to go beyond array length, causing index out of range error when accessing arrivals[i] or departures[j].
Trains overlap as follows:
- Train 1: 1000-1020
- Train 2: 1010-1035
- Train 3: 1025-1040
- Train 4: 1030-1050
At peak, 3 trains overlap, so 3 platforms are needed.
package main import ( "fmt" "sort" ) func minPlatforms(arrivals []int, departures []int) int { sort.Ints(arrivals) sort.Ints(departures) platformsNeeded := 0 maxPlatforms := 0 i, j := 0, 0 for i < len(arrivals) && j < len(departures) { if arrivals[i] <= departures[j] { platformsNeeded++ if platformsNeeded > maxPlatforms { maxPlatforms = platformsNeeded } i++ } else { platformsNeeded-- j++ } } return maxPlatforms } func main() { arrivals := []int{900, 940, 950, 1100, 1500, 1800} departures := []int{910, 1200, 1120, 1130, 1900, 2000} fmt.Println(minPlatforms(arrivals, departures)) }
Go if statements do not require a colon after the condition (unlike Python). The correct syntax is 'if condition {'. The provided code has no syntax errors.
