Given an array of trips, where each trip is an array with two items — start time and end time — write an algorithm that determines how many trips were happening simultaneously during a 24-hour period. Example input: `[[1, 3], [1.2, 4.3], [3.4, 5.6]]`
Anonymous
### ✅ **Solution (JavaScript)** ```js function maxConcurrentTrips(trips) { // Create a list of all events: start (+1) and end (-1) const events = []; for (const [start, end] of trips) { events.push({ time: start, type: 'start' }); events.push({ time: end, type: 'end' }); } // Sort by time; if times are equal, put 'end' before 'start' events.sort((a, b) => a.time === b.time ? (a.type === 'end' ? -1 : 1) : a.time - b.time ); let current = 0; let max = 0; for (const e of events) { if (e.type === 'start') current++; else current--; max = Math.max(max, current); } return max; } // Example: const trips = [[1, 3], [1.2, 4.3], [3.4, 5.6]]; console.log(maxConcurrentTrips(trips)); // Output: 2 ``` --- ### 🧠 **Explanation** * Each trip is represented by two events: * **start time →** adds 1 active trip * **end time →** removes 1 active trip * We combine all start and end times into a single list of events. * We **sort** the events by time. If two events happen at the same time, we handle the **end** event before the **start** event — this prevents counting a trip that starts and ends at the same moment as overlapping. * We **iterate** through the sorted events: * When a trip starts → increase the counter. * When a trip ends → decrease the counter. * Track the **maximum** number of active trips at any moment. * The result is the **maximum number of concurrent trips** within 24 hours.
Check out your Company Bowl for anonymous work chats.