Repository navigation
Expand file tree
/
Copy pathGasStationCircle.java
More file actions
64 lines (59 loc) · 2.18 KB
/
Copy pathGasStationCircle.java
File metadata and controls
64 lines (59 loc) · 2.18 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
package com.interview.array;
/**
* http://www.geeksforgeeks.org/find-a-tour-that-visits-all-stations/
* You can solve this one using kadane wrap since it finds max contiguous sum
* for wrapped array. That start point is a best place to start a tour.
* Test cases
* Check if length of both input array is same
* Check that there exists a path after kadane wrap responds
* Check that there is at least one positive difference before you call kadane
*/
public class GasStationCircle {
public int startTour(int gasAvailable[],int gasRequired[]){
int start = -1;
int end = 0;
int currentGas = 0;
boolean visitedOnce = false;
while(start != end){
currentGas += gasAvailable[end] - gasRequired[end];
if(start == -1){
start = end;
}
if(end == gasAvailable.length-1 && visitedOnce == false){
visitedOnce = true;
}else if(end == gasAvailable.length-1 && visitedOnce == true){
return -1;
}
if(currentGas < 0){
start = -1;
currentGas = 0;
}
end = (end + 1)%gasAvailable.length;
}
return end;
}
/**
* This solution assumes that a tour does exists.
* If it is not guaranteed that tour exists then once you get
* result of kadanewrap make an actual trip to see if value is positive
* @param gasAvailable
* @param gasRequired
* @return
*/
public int startTour1(int gasAvailable[], int gasRequired[]){
int diff[] = new int[gasAvailable.length];
for(int i=0; i < diff.length; i++){
diff[i] = gasAvailable[i] - gasRequired[i];
}
KadaneWrapArray kwa = new KadaneWrapArray();
Triplet t = kwa.kadaneWrap(diff);
return t.start;
}
public static void main(String args[]){
GasStationCircle gsc = new GasStationCircle();
int[] gasAvailable = {8,6,11,13,2,11};
int[] gasRequired = {10,12,6,4,9,8};
System.out.println(gsc.startTour(gasAvailable, gasRequired));
System.out.println(gsc.startTour1(gasAvailable, gasRequired));
}
}