Algorithm for truck moving around a circle of gas stations

前端 未结 11 1391
陌清茗
陌清茗 2020-12-13 07:08

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

11条回答
  •  猫巷女王i
    2020-12-13 07:45

    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:

    1. Test case A : { 1, 2, 3, 4, 5 }, B : { 1, 3, 2, 4, 5 } --> index 2
    2. Test case A : {2,2,1}, B : {2,1,2} index --> 0
    3. Test case A : {1,2}, B {2,1} --> index 1
    4. Test case A : {1,2,1}, B {2,1,3} --> index -1

提交回复
热议问题