Skip to content

Instantly share code, notes, and snippets.

@sethkontny
Forked from junjiah/GasStation.java
Created January 18, 2014 06:45
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 sethkontny/8487106 to your computer and use it in GitHub Desktop.
Save sethkontny/8487106 to your computer and use it in GitHub Desktop.
solved "Gas Station" on LeetCode http://oj.leetcode.com/problems/gas-station/
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
size = gas.length;
if (size == 0) return -1;
int src = 0, dest = 0, balance = 0;
while (true) {
if (balance + gas[dest] - cost[dest] >= 0) {
balance += gas[dest] - cost[dest];
dest = next(dest);
if (dest == src) return src;
}
else {
if (next(dest) <= src) break;
src = next(dest);
dest = src;
balance = 0;
}
}
return -1;
}
private int next(int i) {
return (i+1) % size;
}
private int size;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment