You have a truck moving around a circular track with gas stations spaced out around the circle. Each station has a finite amount of gas. The gas tank on the truck is infinit
static int find(int A[], int B[]) {
for (int start = 0; start < A.length; start++) {
int x = findIndex(A, B, start);
if (x != -1)
return x;
}
return -1;
}
static int findIndex(int A[], int B[], int start) {
int total=0;
int N = A.length;
for (int i = start; i < start + A.length; i++) {
int c = A[i % N] - B[i % N];
total += c;
if (total < 0) {
total = 0;
return -1;
}
}
return start;
}
Test cases:
A : { 1, 2, 3, 4, 5 }, B : { 1, 3, 2, 4, 5 } --> index 2A : {2,2,1}, B : {2,1,2} index --> 0A : {1,2}, B {2,1} --> index 1 A : {1,2,1}, B {2,1,3} --> index -1