-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGasStation.java
More file actions
83 lines (71 loc) · 2.06 KB
/
Copy pathGasStation.java
File metadata and controls
83 lines (71 loc) · 2.06 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class MySolution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas.length == 1 && cost.length == 1) {
return gas[0] >= cost[0] ? 0 : -1;
}
for (int i = 0; i < cost.length; i++) {
if (cost[i] > gas[i]) {
continue;
}
int tank = 0;
int startIndex = i;
tank += gas[startIndex];
int index = startIndex+1;
while (index != startIndex) {
if (index == cost.length) {
index = 0;
if (index == startIndex) {
break;
}
}
if (index == 0) {
tank -= cost[cost.length-1];
}
else
tank -= cost[index-1];
if (tank < 0) {
break;
}
tank += gas[index];
if (tank <= 0) {
break;
}
index++;
}
if (startIndex == 0) {
if (index == startIndex && tank >= 0 && tank - cost[cost.length-1] >= 0) {
return startIndex;
}
}
else {
if (index == startIndex && tank >= 0 && tank - cost[startIndex-1] >= 0) {
return startIndex;
}
}
}
return -1;
}
}
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int gasSum = 0;
int costSum = 0;
int result = 0;
int total = 0;
for (int i = 0; i < cost.length; i++) {
gasSum += gas[i];
costSum += cost[i];
}
if (gasSum < costSum) {
return -1;
}
for (int i = 0; i < cost.length; i++) {
total += gas[i] - cost[i];
if (total < 0) {
total = 0;
result = i+1;
}
}
return result;
}
}