Electric Bus Loop
Medium · Greedy & Intervals · about 20 min
An electric bus drives a circular route through stations 0, 1, ..., n - 1 and back to 0. At station i it gains charge[i] units of battery, and driving from station i to the next station costs cost[i] units (from the last station it drives back to station 0).
The bus starts at one station with an empty battery, charges there, and must drive one full loop back to that station. The battery may reach exactly 0, but never go below 0.
Return the smallest station index the bus can start from, or -1 if no start works.
- 1 ≤ n ≤ 10^5, all values 0 to 10^4.
bus_loop_start([3, 1, 4], [2, 3, 2]) → 2
Hints
- If the total charge is less than the total cost, the answer is -1.
- Try station 0 first and follow the battery level. Where it goes below zero, think about which starts you just ruled out.
- Every station from the current start to the failing one is ruled out, so restart just after the failing station with an empty battery.
Learn the pattern first: the Greedy & Intervals lesson.
More Greedy & Intervals problems
- Stepping Stones Across the Creek (Easy)
- Artist Blocks in a Playlist (Easy)
- Squeeze In a Booking (Medium)
- Clear the Talk Schedule (Medium)
- Team Bonus Tokens (Hard)
- Road Trip Fuel Stops (Hard)