Ring Line Tram Battery

HardgreedyAlso known as Gas Station

A city is testing a battery tram on its ring line. The stops are numbered 0 to n - 1 around the loop, and after the last stop the tram comes back to stop 0. Each stop has a charging pad that adds charge[i] units to the battery while the tram waits there. Driving from stop i to the next stop uses cost[i] units.

For the test run, the tram is placed at one stop with a flat battery. It charges there, drives on, charges at the next stop, and so on. The battery must never run out between stops. The engineers want to know where to place the tram 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 level 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

Start at stop 3: charge 4, drive costs 1, arrive at stop 0 with 3. Charge 3 (6), drive 2, arrive at stop 1 with 4. Charge 1 (5), drive 3, arrive at stop 2 with 2. Charge 2 (4), drive 3, arrive back at stop 3 with 1. Starting at stop 0 fails: 3 - 2 = 1, then 1 + 1 - 3 = -1 before stop 2. Stops 1 and 2 fail on their first drive.

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

All the pads together give 6 units, but the whole loop costs 7. No starting stop can make up for a loop that uses more than it gives.

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. The first stop that completes the loop is the answer.

Each simulation can take up to n steps, so this is O(n²): with 100,000 stops that is up to 10 billion steps. The waste: when a run from stop 2 dies at stop 7, the brute force then tries stops 3, 4, 5 and 6, which are doomed 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