Skip to content

Commit 4545c1c

Browse files
authored
2022-09-23 update: added "Gas Station" (#116)
1 parent 75ef693 commit 4545c1c

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,7 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
466466
| 128. Longest Consecutive Sequence | [Link](https://leetcode.com/problems/longest-consecutive-sequence/) | [Link](./src/main/java/com/smlnskgmail/jaman/leetcodejava/medium/LongestConsecutiveSequence.java) |
467467
| 129. Sum Root to Leaf Numbers | [Link](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | [Link](./src/main/java/com/smlnskgmail/jaman/leetcodejava/medium/SumRootToLeafNumbers.java) |
468468
| 133. Clone Graph | [Link](https://leetcode.com/problems/clone-graph/) | [Link](./src/main/java/com/smlnskgmail/jaman/leetcodejava/medium/CloneGraph.java) |
469+
| 134. Gas Station | [Link](https://leetcode.com/problems/gas-station/) | [Link](./src/main/java/com/smlnskgmail/jaman/leetcodejava/medium/GasStation.java) |
469470
| 138. Copy List with Random Pointer | [Link](https://leetcode.com/problems/copy-list-with-random-pointer/) | [Link](./src/main/java/com/smlnskgmail/jaman/leetcodejava/medium/CopyListWithRandomPointer.java) |
470471
| 142. Linked List Cycle II | [Link](https://leetcode.com/problems/linked-list-cycle-ii/) | [Link](./src/main/java/com/smlnskgmail/jaman/leetcodejava/medium/LinkedListCycleII.java) |
471472
| 143. Reorder List | [Link](https://leetcode.com/problems/reorder-list/) | [Link](./src/main/java/com/smlnskgmail/jaman/leetcodejava/medium/ReorderList.java) |
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
// https://leetcode.com/problems/gas-station/
4+
public class GasStation {
5+
6+
private final int[] gas;
7+
private final int[] cost;
8+
9+
public GasStation(int[] gas, int[] cost) {
10+
this.gas = gas;
11+
this.cost = cost;
12+
}
13+
14+
public int solution() {
15+
int tmpSum = 0;
16+
int index = 0;
17+
int sum = gas[0] - cost[0];
18+
for (int i = 1; i < gas.length; i++) {
19+
if (sum < 0) {
20+
index = i;
21+
tmpSum += sum;
22+
sum = 0;
23+
}
24+
sum += gas[i] - cost[i];
25+
}
26+
sum += tmpSum;
27+
return sum >= 0 ? index : -1;
28+
}
29+
30+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertEquals;
6+
7+
public class GasStationTest {
8+
9+
@Test
10+
public void defaultTest() {
11+
assertEquals(
12+
3,
13+
new GasStation(
14+
new int[]{1, 2, 3, 4, 5},
15+
new int[]{3, 4, 5, 1, 2}
16+
).solution()
17+
);
18+
}
19+
20+
}

0 commit comments

Comments
 (0)