Created
September 27, 2017 13:08
-
-
Save anil477/1179e7fe831c752ceefbbab30e527570 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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