Scooter Convoys
Medium · Stack & Monotonic Stack · about 25 min
Delivery scooters ride along a one-lane road toward a depot at mile target. Scooter i starts at mile positions[i] and rides at speeds[i] miles per hour. All positions are different and less than target; all speeds are positive.
Nobody can overtake. When a faster scooter catches up with a slower one, it slows down and they ride together as one convoy at the slower speed. A scooter that catches up exactly at the depot still counts as part of that convoy. A single scooter riding alone is a convoy too.
Return the number of convoys that reach the depot.
Example: scooter_convoys(10, [9, 8, 6], [1, 4, 5]) → 1 (the scooter at 9 needs 1 hour; the others would be faster alone, so they all join it)
Example: scooter_convoys(10, [3, 7], [2, 1]) → 2 (3.5 hours and 3 hours: the one behind is slower)
Constraints: 0 to 100,000 scooters; target up to 1,000,000; speeds up to 1,000,000. The inputs are listed in any order.
Hints
- The scooter closest to the depot is never slowed down. Process the scooters from closest to farthest.
- Work out when each scooter would arrive if it rode alone. A scooter behind that would arrive no later than the convoy in front joins it.
- Only the time of the convoy in front matters: start a new convoy only when a scooter would arrive strictly later. Compare fractions by cross-multiplying.
Learn the pattern first: the Stack & Monotonic Stack lesson.
More Stack & Monotonic Stack problems
- Config Bracket Check (Easy)
- Cancelling Beads (Easy)
- Calculator Tape (Easy)
- Lightest Parcel on the Pile (Medium)
- Banner Expander (Medium)
- Taller Friend at the Round Table (Medium)
- Biggest Skyline Billboard (Hard)