I got this question in an interview and I was not able to solve it.
You have a circular road, with N number of gas stations. You know the ammount of gas that each station has. You know the ammount of gas you need to GO from one station to the next one. Your car starts with 0 gas. The question is: Create an algorithm, to know from which gas station you must start driving to COMPLETE the circular PATH. It does not specify that you must visit all stations. You can only drive clockwise.
I had to do it in c#
The only code I started is with a GasStation entity
class GasStation
int gasAtStation;
int gasToMoveToNextStationNeeded;
string nameOfGasStation;
GasTation wheretoStart(List<GasStation> list)
{
}
I did it this way:
static void Main(string[] args)
{
int[] gasOnStation = {1, 2, 0, 4};
int[] gasDrivingCostTonNextStation = {1, 1,2, 1};
FindStartingPoint(gasOnStation, gasDrivingCostTonNextStation);
}
static void FindStartingPoint(int[] gasOnStation, int[] gasDrivingCosts)
{
// Assume gasOnStation.length == gasDrivingCosts.length
int n = gasOnStation.Length;
int[] gasEndValues = new int[n];
int gasValue = 0;
for (int i = 0; i < n; i++)
{
gasEndValues[i] = gasValue;
gasValue += gasOnStation[i];
gasValue -= gasDrivingCosts[i];
}
if (gasValue < 0)
{
Console.WriteLine("Instance does not have a solution");
Console.ReadLine();
}
else
{
// Find the minimum in gasEndValues:
int minI = 0;
int minEndValue = gasEndValues[0];
for (int i = 1; i < n; i++)
{
if (gasEndValues[i] < minEndValue)
{
minI = i;
minEndValue = gasEndValues[i];
}
}
Console.WriteLine("Start at station: " + minI);
Console.ReadLine();
}
}
Thanks
If we define that a trip from station A to B comprises of the GasAtStation A and TripCost. Then for each trip we have that TripBalance = GasAtStation-TripCost
The sum of all the trip balances must be greater or equal to zero, otherwise a solution does not exist. The solution consists of having a list with the trip balances for each gas station and iterate through the items keeping a variable for the tripBalance, if the tripBalance becomes negative, then the trip should start at the next gas station, if so, we reset the tripBalance and we keep processing until we check the last entry in the list:
I tested it using the following code:
See that the passed values are the ones worked out from the example given at the question header. In this case, the answer is that the last gas station in our list should be the first gas station. Finally, if there is not solution, the method returns -1.
Another example to cover where the stations with higher gas are not the solution:
This is optimized case of @George Duckett's answer.
If you reached your start station - problem solved.
If on some station you do not have enough fuel to reach next one
If you had gone counterclockwise to already visited station - bad luck, there is not enough fuel on stations to go full circle.