Bhavya

Code -> Break -> Fix -> Blog

Petrol Pump (Gas station) Problem (C#)

1 Comment

Problem Description:

We have a group of Petrol pump on a Circular Road (Ring Road) say P(1), P(2), P(3)…P(N).

Each Petrol pump has some amount of fuel with it say P(1) has F(1), P(2) has F(2) …. P(N) has F(N).

Distance between two consecutive Petrol pumps are D(1), D(2), D(3) … D(N).So distance between P(1) and P(2) is D(1) and P(2) and P(3) is D(2)…. P(N) and P(1) is D(N).

Find the starting point such that the vehicle should be make the full circle.


static int GetStartPoint(int[] fuel, int[] distance)
{
if (fuel == null || distance == null || fuel.Length == 0 || distance.Length == 0)
{
//invalid input.
return -1;
}

if (fuel.Sum() < distance.Sum())
{
// No StartPoint found.
return -2;
}

int startPoint = 0;
int pumpLength = fuel.Length - 1;

int leftOverFuel = 0;
int i = 0;

do
{
if (i > pumpLength)
{
// No StartPoint found.
return -2;
}

if (fuel[i] + leftOverFuel < distance[i])
{
startPoint = i++;
}
else
{
leftOverFuel += fuel[i] - distance[i];
if (i == pumpLength)
{
i = 0;
}
else
{
i++;
}
}
} while (i != startPoint);

return startPoint + 1;
}

Advertisements

One thought on “Petrol Pump (Gas station) Problem (C#)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s