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
One easy way of solving this is using a brute force method. i.e. try every posibility and throw out ones that don’t work.
i.e. Start at each gas station in turn (repeat below for each starting station).
(gas >= gasToMoveToNextStationNeeded)Edit As per @Vash’s answer, As an improvement when deciding where to start, discount stations that don’t have enough gas themselves to get to the next station and working through starting stations in order of amount of gas (descending).
Note, this assumes we visit all gas stations. Will need refinement for skipping gas stations if you need an optimal solution (question doesn’t specify this).