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.
Worked example, as suggested in a comment by Handcraftsman:
Label nodes 0 through 4
node: 0,1,2,3,4
fuel: 1,3,4,4,1
dist: 1,4,2,2,2
First calculate F_0_i for i = 1, 2, 3, 4, 0
Start at node 0 with 0 fuel.
f_0_1 = 0 + 1 - 1 = 0, min score 0, node 1;
f_0_2 = 0 + 3 - 4 = -1, min score -1, node 2;
f_0_3 = -1 + 4 - 2 = 1;
f_0_4 = 1 + 4 - 2 = 3;
f_0_0 = 3 + 1 - 2 = 2;
f_0_0 is non-negative, so there is enough fuel.
The minimum score was -1, at node 2, so the result is node 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With