java: add «134. Gas Station»
URL: https://leetcode.com/problems/gas-station/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
0c8d6c1b2d
commit
9bcb76c340
1 changed files with 26 additions and 0 deletions
26
java/gas-station.java
Normal file
26
java/gas-station.java
Normal file
|
@ -0,0 +1,26 @@
|
|||
class Solution {
|
||||
public int canCompleteCircuit(int[] gas, int[] cost) {
|
||||
int totalGas = 0, totalCost = 0;
|
||||
|
||||
int currentGas = 0, start = 0;
|
||||
for (var i = 0; i < gas.length; ++i) {
|
||||
totalGas += gas[i];
|
||||
totalCost += cost[i];
|
||||
|
||||
currentGas += gas[i] - cost[i];
|
||||
if (currentGas < 0) {
|
||||
// we can't reach this point, have to start from the next one
|
||||
currentGas = 0;
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (totalGas < totalCost) {
|
||||
// not enough gas from any station
|
||||
return -1;
|
||||
}
|
||||
|
||||
// there's a unique solution, iff it exists
|
||||
return start;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue