Created
March 16, 2020 18:56
-
-
Save ShikaSD/3dc0e57da9c8ef3f0ced5402620b97f1 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 Solution { | |
public int canCompleteCircuit(int[] gas, int[] cost) { | |
int min = Integer.MAX_VALUE; | |
int start = -1; | |
int current = 0; | |
for (int i = 0; i < gas.length; i++) { | |
current += gas[i] - cost[i]; | |
if (current < min) { | |
min = current; | |
start = i + 1; | |
} | |
} | |
if (start == -1) { | |
return -1; | |
} | |
// System.out.println("min = " + min + " start = " + start); | |
current = 0; | |
for (int i = start; i < gas.length; i++) { | |
current += gas[i] - cost[i]; | |
if (current < 0) { | |
return -1; | |
} | |
} | |
for (int i = 0; i < start; i++) { | |
current += gas[i] - cost[i]; | |
if (current < 0) { | |
return -1; | |
} | |
} | |
return start == gas.length ? 0 : start; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment