g0101_0200.s0134_gas_station.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0101_0200.s0134_gas_station;
// #Medium #Top_Interview_Questions #Array #Greedy
// #2022_06_24_Time_2_ms_(94.26%)_Space_62.5_MB_(87.11%)
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sumGas = 0;
int sumCost = 0;
int curGas = 0;
int result = -1;
for (int i = 0; i < gas.length; i++) {
curGas += gas[i] - cost[i];
// re-calculate the starting point
if (curGas < 0) {
result = -1;
curGas = 0;
} else if (result == -1) {
// set initial starting point
result = i;
}
sumGas += gas[i];
sumCost += cost[i];
}
if (sumGas < sumCost) {
return -1;
}
return result;
}
}