Skip to content

Commit 2fe9afd

Browse files
author
Yi Gu
committed
[Gas Station] Add a solution to Gas Station
1 parent 3af287d commit 2fe9afd

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Array/GasStation.swift

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/gas-station/
3+
* Primary idea: use currentSum and total to keep track of the gas and cost,
4+
* change start index when currentSum is less than 0
5+
*
6+
* Time Complexity: O(n), Space Complexity: O(1)
7+
*
8+
*/
9+
10+
class GasStation {
11+
func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int {
12+
guard gas.count == cost.count else {
13+
return -1
14+
}
15+
16+
var currentSum = 0
17+
var total = 0
18+
var startIdx = 0
19+
20+
for (i, curtGas) in gas.enumerated() {
21+
currentSum += (curtGas - cost[i])
22+
total += (curtGas - cost[i])
23+
24+
if currentSum < 0 {
25+
startIdx = i + 1
26+
currentSum = 0
27+
}
28+
}
29+
30+
if total < 0 {
31+
return -1
32+
}
33+
return startIdx
34+
}
35+
}

0 commit comments

Comments
 (0)