import java.util.*;
/**
* Suppose there is a circle. There are n petrol pumps on that circle. You are given two sets of data.
* 1. The amount of petrol that petrol pump will give.
* 2. Distance from that petrol pump to the next petrol pump.
*
* Calculate the first point from where a truck will be able to complete the circle
* (The truck will stop at each petrol pump and it has infinite capacity).
*
* Assume for 1 litre petrol, the truck can go 1 unit of distance.
*
* For example, let there be 4 petrol pumps with amount of petrol and distance to
* next petrol pump value pairs as {4, 6}, {6, 5}, {7, 3} and {4, 5}.
* The first point from where truck can make a circular tour is 2nd petrol pump.
*
* Output should be “start = 1″ (index of 2nd petrol pump).
*
*/
class Ideone {
public static void main
(String[] args
){ //ith element in petrol represents petrol available at pump i and distances[i] represents distance from i to i+1 petrol pump
int[] petrol = {4,6,5,4};
int[] distances = {6,5,3,5};
//Keep two pointers to track start and end points of traversal path
//Also move in one direction. Once you found you cannot move forward with existing petrol, extend in other direction
//When starting end end pointers are equal, you have completed the circular path
int startIndex = 0;
int endIndex = 0;//Max Index + 1
int leftOverPetrol = 0;
while(true){
int totalPetrolAvailable = leftOverPetrol + petrol[endIndex];
if(distances[endIndex] > totalPetrolAvailable){
// Doesn't have any fuel to move forward. So include last point(move backward)
if(startIndex == 0){
startIndex = petrol.length - 1;//Set pointer to last petrol pump
}else{
startIndex--; //Include previous pump to start index
}
leftOverPetrol = leftOverPetrol + petrol[startIndex] - distances[startIndex];
}else{
leftOverPetrol = totalPetrolAvailable - distances[endIndex];
if(endIndex == petrol.length -1){
endIndex = 0;
}else{
endIndex++;
}
}
if(startIndex == endIndex) break; //Made a circular loop
}
if(leftOverPetrol >= 0){
System.
out.
println("Start index to complete loop => "+ startIndex
); }else{
System.
out.
println("Circular loop not possible"); }
}
//Approach 2 : We can create a Queue to store the current tour. We first enqueue first petrol pump to the queue, we keep enqueueing petrol pumps till we either complete the tour, or current amount of petrol becomes negative. If the amount becomes negative, then we keep dequeueing petrol pumps till the current amount becomes positive or queue becomes empty.
}