Hints — p82 Gas Station
-
First check: if
sum(gas) < sum(cost), return -1 immediately. Necessary condition. -
Try simulating from each start (O(n²)). Then look for an invariant that lets you skip ahead.
-
Skip lemma: if tank goes negative at station i starting from s, then no j in [s, i] is valid. Why?
T(j, i) = T(s, i) - T(s, j-1) < 0sinceT(s, j-1) ≥ 0. -
Therefore on failure at i, reset
start = i + 1andtank = 0. Continue the same pass. -
After one pass, if
total = sum(gas - cost) ≥ 0, returnstart; else -1.
If stuck: see solution.py.