I appeared in an interview. I stuck in one question. I am asking the same.
Question: There is circular road is given. That road contains number
of petrol pumps. Each petrol pump have given amount of petrol.
Distance between each two consecutive petrol pump is also given. Now
there is a vehicle is given having empty fuel tank of limitless
capacity. Build an algorithm so that vehicle can cover complete round
without any backtracking. It is given that such path is definitely
possible.
Input: (int fuel[], int distance[])
Output: petrol pump index from where vehicle can make complete round of circular road.
My approaches:
-
Check from each petrol pump, if fuel tank is empty in between path, move to next petrol pump. and start the same process again. This algorithm takes O(N^2), here N = number of petrol pumps.
-
Then I move to the Binary search concept, to reduce the complexity to O(n*logn). But I failed to conclude the solution. I messed up in this solution.
-
Then I try to apply some intelligence, by choosing that petrol pump whose left petrol is maximum in between that two petrol pumps.
(This may be equivalent to the algorithm Evgeny Kluev posted, which I don’t understand. If so, that answer has priority.)
Let F_i_j be the net, signed amount of fuel in the tank on arriving at j having started at i with zero fuel in the tank before filling at i.
Calculate F_0_i for every node i by working around the circle adding fuel at each node and subtracting the fuel cost of each edge.
If F_0_0, the net fuel at the end of a circuit starting at 0, is negative, then there is not enough fuel in the system (this is not supposed to happen according to the problem statement).
If no F_0_i is negative, report 0 as result.
Otherwise, find the node s with the most negative value of F_0_s. Pick s as the starting node.
For any node i, F_s_i is equal to F_0_i + abs(F_0_s). Since F_0_s is the most negative F_0_i, that makes F_s_i non-negative.