Ring Line Tram Battery

HardgreedyAlso known as Gas Station

A city is testing a battery tram on its ring line. Stops are numbered 0 to n - 1, and after the last stop the tram returns to stop 0. Waiting at stop i adds charge[i] units; driving from stop i to the next uses cost[i].

The tram starts at one stop with a flat battery and must never run out between stops. Where should the engineers place it so it can drive one full loop?

Your task

Write startingStop(charge, cost). The tram starts at stop s with 0 units, adds charge[s], spends cost[s] to reach the next stop, adds that stop's charge, and so on, until it is back at s. The battery must never drop below 0 on arrival at a stop. Return the smallest stop index from which the full loop works, or -1 if none does.

The battery has no upper limit. Arriving with exactly 0 units is fine.

startingStop(charge: int[], cost: int[]) → int

Examples

Example 1
Input
charge = [3, 1, 2, 4]
cost = [2, 3, 3, 1]
Output
3
Why

Starting at stop 3, the tram charges 4 units and drives 1, so it arrives at stop 0 with 3. It charges 3 (total 6), drives 2 and arrives at stop 1 with 4. It charges 1 (total 5), drives 3 and arrives at stop 2 with 2. It charges 2 (total 4), drives 3 and is back at stop 3 with 1. Starting at stop 0 fails: the tram leaves with 3 - 2 = 1, reaches stop 1, and then 1 + 1 - 3 = -1 before it can reach stop 2. Stops 1 and 2 already fail on their first drive.

Example 2
Input
charge = [2, 2, 2]
cost = [3, 2, 2]
Output
-1
Why

The pads give 6 units in total, but the loop costs 7. No start can make up for that.

Constraints

  • 1 ≤ charge.length = cost.length ≤ 100,000
  • 0 ≤ charge[i], cost[i] ≤ 10,000
Start with brute force

Try every stop as the start and simulate a full loop, stopping early if the battery goes negative.

Each simulation takes up to n steps, so the total is O(n²), which is up to 10 billion steps for 100,000 stops. Much of that work is wasted. If a run from stop 2 fails at stop 7, the approach then tries stops 3 to 6, and they are doomed to fail for the same reason.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code