Skip to content

Instantly share code, notes, and snippets.

@anil477
Created September 27, 2017 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/1179e7fe831c752ceefbbab30e527570 to your computer and use it in GitHub Desktop.
Save anil477/1179e7fe831c752ceefbbab30e527570 to your computer and use it in GitHub Desktop.
class GasStation {
public static int canCompleteCircuit(int[] gas, int[] cost)
{
if(gas == null || cost == null) return -1;
int total = 0;
int upToNow = 0;
int startPos = 0;
for(int i=0; i<gas.length; i++)
{
int delta = gas[i] - cost[i];
if(upToNow >= 0)
{
upToNow += delta;
}
else
{
upToNow = delta;
startPos = i;
}
total += delta;
// System.out.println( "Delta: " + delta + " Total: " + total );
}
return total >= 0 ? startPos : -1;
}
public static void main(String[] args)
{
int[] gas = {6,3,7};
int[] cost = {4,6,3};
System.out.println(canCompleteCircuit(gas, cost));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment