Skip to content

Instantly share code, notes, and snippets.

@jhidajat
Created April 5, 2022 15:35
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 jhidajat/c83f1f6978dccf1be0ee5aafebf900ac to your computer and use it in GitHub Desktop.
Save jhidajat/c83f1f6978dccf1be0ee5aafebf900ac to your computer and use it in GitHub Desktop.
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int total_tank = 0;
int curr_tank = 0;
int starting_station = 0;
for (int i = 0; i < n; ++i) {
total_tank += gas[i] - cost[i];
curr_tank += gas[i] - cost[i];
// If one couldn't get here,
if (curr_tank < 0) {
// Pick up the next station as the starting one.
starting_station = i + 1;
// Start with an empty tank.
curr_tank = 0;
}
}
return total_tank >= 0 ? starting_station : -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment