-
Notifications
You must be signed in to change notification settings - Fork 75
/
134_Gas_Station
69 lines (54 loc) · 1.5 KB
/
134_Gas_Station
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
Leetcode 134: Gas Station
Detailed video Explanation: https://youtu.be/xmJZSYSvgfE
========================================
C++:
----
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int total_surplus = 0;
int surplus = 0;
int S = 0;
for(int i = 0; i < n; ++i){
total_surplus += gas[i] - cost[i];
surplus += gas[i] - cost[i];
if(surplus < 0){
surplus = 0;
S = i+1;
}
}
return (total_surplus < 0) ? -1 : S;
}
};
Java:
-----
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int total_surplus = 0;
int surplus = 0;
int S = 0;
for(int i = 0; i < n; ++i){
total_surplus += gas[i] - cost[i];
surplus += gas[i] - cost[i];
if(surplus < 0){
surplus = 0;
S = i+1;
}
}
return (total_surplus < 0) ? -1 : S;
}
}
Python3:
--------
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n, total_surplus, surplus, S = len(gas), 0, 0, 0
for i in range(n):
total_surplus += gas[i] - cost[i]
surplus += gas[i] - cost[i]
if surplus < 0:
surplus = 0
S = i+1
return -1 if (total_surplus < 0) else S