Skip to content

Commit cc76ce7

Browse files
committed
Gas Station
1 parent 3589fd3 commit cc76ce7

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package leetcode.medium;
2+
3+
public class GasStation {
4+
5+
int canCompleteCircuit(int[] gas, int[] cost) {
6+
int totalGas = 0, totalCost = 0;
7+
8+
// Calculate total gas and total cost
9+
for (int i = 0; i < gas.length; i++) {
10+
totalGas += gas[i];
11+
totalCost += cost[i];
12+
}
13+
14+
// If total gas is less than total cost, return -1
15+
if (totalGas < totalCost) {
16+
return -1;
17+
}
18+
19+
int currentGas = 0, startIndex = 0;
20+
// Iterate through the gas stations
21+
for (int i = 0; i < gas.length; i++) {
22+
currentGas += gas[i] - cost[i];
23+
24+
// If current gas is negative, reset start index and current gas
25+
if (currentGas < 0) {
26+
startIndex = i + 1;
27+
currentGas = 0;
28+
}
29+
}
30+
31+
// Return the starting index if a valid circuit exists
32+
return startIndex;
33+
}
34+
35+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package leetcode.medium;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class GasStationTest {
8+
9+
private final GasStation gasStation;
10+
11+
GasStationTest() {
12+
gasStation = new GasStation();
13+
}
14+
15+
@Test
16+
void testCanCompleteCircuit1() {
17+
int[] gas = {1, 2, 3, 4, 5};
18+
int[] cost = {3, 4, 5, 1, 2};
19+
assertEquals(3, gasStation.canCompleteCircuit(gas, cost));
20+
}
21+
22+
@Test
23+
void testCanCompleteCircuit2() {
24+
int[] gas = {2, 3, 4};
25+
int[] cost = {3, 4, 3};
26+
assertEquals(-1, gasStation.canCompleteCircuit(gas, cost));
27+
}
28+
29+
@Test
30+
void testCanCompleteCircuit3() {
31+
int[] gas = {5, 1, 2, 3, 4};
32+
int[] cost = {4, 4, 1, 5, 1};
33+
assertEquals(4, gasStation.canCompleteCircuit(gas, cost));
34+
}
35+
36+
@Test
37+
void testCanCompleteCircuit4() {
38+
int[] gas = {1, 2, 3};
39+
int[] cost = {2, 2, 2};
40+
assertEquals(1, gasStation.canCompleteCircuit(gas, cost));
41+
}
42+
}

0 commit comments

Comments
 (0)