Skip to content

Instantly share code, notes, and snippets.

@ShikaSD
Created March 16, 2020 18:56
Show Gist options
  • Save ShikaSD/3dc0e57da9c8ef3f0ced5402620b97f1 to your computer and use it in GitHub Desktop.
Save ShikaSD/3dc0e57da9c8ef3f0ced5402620b97f1 to your computer and use it in GitHub Desktop.
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