Wednesday, July 2, 2014

[Leetcode] Gas Station

Problem

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.

Algorithm

Brute Force O(n^2)
Iterating each station as the starting station, calculate the remaining gas when arriving other n-1 stations. If at some point, the remaining gas is below zero, choosing this as the starting station cannot complete the circle. 

Linear Solution

Claim: Assume, starting from station A, we can reach station B, but cannot reach station B+1. Thus, we cannot find a middle point C between A and B, that can reach B+1 station.

Proof: Suppose we can start from C, where C lies between A and B, and reach station B+1. Since we know we can reach C from A, and we can reach B+1 from C, then we can reach B+1 from A, which contradicts with our assumption. 

With above claim, we can devise the following algorithm shown in the code. 

Code


No comments:

Post a Comment