We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 3af287d commit 2fe9afdCopy full SHA for 2fe9afd
Array/GasStation.swift
@@ -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
32
33
+ return startIdx
34
35
+}
0 commit comments