Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c68fd0d

Browse files
solves gas station
1 parent 9cae15e commit c68fd0d

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@
120120
| 130 | [Surrounded Regions](https://leetcode.com/problems/surrounded-regions) | [![Java](assets/java.png)](src/SurroundedRegions.java) | |
121121
| 131 | [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning) | [![Java](assets/java.png)](src/PalindromePartitioning.java) | |
122122
| 133 | [Clone Graph](https://leetcode.com/problems/clone-graph) | [![Java](assets/java.png)](src/CloneGraph.java) | |
123-
| 134 | [Gas Station](https://leetcode.com/problems/gas-station) | | |
123+
| 134 | [Gas Station](https://leetcode.com/problems/gas-station) | [![Java](assets/java.png)](src/GasStation.java) | |
124124
| 136 | [Single Number](https://leetcode.com/problems/single-number) | [![Java](assets/java.png)](src/SingleNumber.java) [![Python](assets/python.png)](python/single_number.py) | |
125125
| 137 | [Single Number II](https://leetcode.com/problems/single-number-ii) | | |
126126
| 138 | [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer) | | |

src/GasStation.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// https://leetcode.com/problems/gas-station
2+
// T: O(n)
3+
// S: O(1)
4+
5+
public class GasStation {
6+
public int canCompleteCircuit(int[] gas, int[] cost) {
7+
if (sum(gas) < sum(cost)) return -1;
8+
9+
int startIndex = 0;
10+
for (int i = 0, total = 0 ; i < gas.length ; i++) {
11+
total += gas[i] - cost[i];
12+
if (total < 0) {
13+
total = 0;
14+
startIndex = i + 1;
15+
}
16+
}
17+
return startIndex;
18+
}
19+
20+
private int sum(int[] array) {
21+
int sum = 0;
22+
for (int element : array) {
23+
sum += element;
24+
}
25+
return sum;
26+
}
27+
}

0 commit comments

Comments
 (0)