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-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0101_0200.s0134_gas_station;
// #Medium #Top_Interview_Questions #Array #Greedy
// #2022_02_22_Time_3_ms_(61.54%)_Space_81.3_MB_(7.19%)
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;
}
}