Problem
Problem page: https://leetcode.com/problems/gas-station/
Topics: Greedy
Difficulty: Medium
There are N gas stations along a circular route, where the amount of gas at station i is
gas[i].You have a car with an unlimited gas tank and it costs
cost[i]of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
Analysis
The basic idea is to first work out an array of "balances". At each station, take the gas left in the tank, add the gas you can pick up there, and subtract the gas it takes to reach the next station. That's the "balance" at that station. On a valid route, the balance can't drop below 0 at any point along the way.
There are two ways to cut down on the work and bring the time complexity down to O(n) from O(n*n) for brute-force search.
First, suppose you start at A and the balance drops below 0 at D. Set the next starting point to D (I think you could set it to E, the point after D, but I used D to keep the code simple). Here's why: the running sums from A through C are all >=0, and D must be a negative number whose absolute value is greater than the sum so far. That's what makes the balance at D negative.
Suppose you set the new starting point to B instead of D. We know A>=0 (otherwise the balance would already be negative at A). Since the balance A+B+C isn't enough to cover the cost at D, B+C has even less to cover it.
Suppose you set the new starting point to C. We know A+B>=0, since otherwise the balance A+B wouldn't be enough to cover the cost at C. Since the balance A+B+C isn't enough to cover the cost at D, the balance at C has even less to cover it.
...
You can think of it this way: every prefix sum of a valid (or locally valid) route is nonnegative. If there isn't enough gas left to get past the current point, you still can't get past it after dropping a prefix of any length.
Second, you can keep track of the smallest prefix sum. The route in the problem is a loop, but the code uses a linear array. When you start somewhere in the array and reach the end, you have to wrap around to the beginning and keep going until you're back where you started. The first trick already guarantees that no element at the end of the array gets counted in two separate sums. It should be possible to avoid counting the elements at the beginning twice, too. Use a variable to store the smallest running sum seen while adding up the elements at the beginning. Then, on any pass, if the total balance from the elements at the end is still enough to cover the cost of that smallest prefix sum at the beginning, the route is valid (no problem?).
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-gas-station/
