-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathP30.java
More file actions
45 lines (33 loc) · 1002 Bytes
/
P30.java
File metadata and controls
45 lines (33 loc) · 1002 Bytes
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
package stack_and_queue;
// Find the first circular tour that visits all Petrol Pumps
public class P30 {
public int tour(int[] petrol, int[] distance) {
int start = 0;
int end = petrol.length -1 ;
int i = start;
int currPetrol = 0; int count = 0;
while(i % (petrol.length) != end) {
if(i == 0)
count++;
currPetrol += petrol[i];
if(currPetrol < distance[i]) {
if(count >= 2) return -1;
start = (i + 1) % (petrol.length);
if(start == 0) return -1;
currPetrol = 0;
end = i % petrol.length;
}
else {
currPetrol -= distance[i];
}
i++;
i %= petrol.length;
}
currPetrol += petrol[end];
if(currPetrol < distance[end])
return -1;
return start;
}
public static void main(String[] args) {
}
}