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:
Matej Focko 2025-01-05 21:52:06 +01:00
parent 0c8d6c1b2d
commit 9bcb76c340
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

26
java/gas-station.java Normal file
View 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;
}
}