Algorithm for truck moving around a circle of gas stations

前端 未结 11 1375
陌清茗
陌清茗 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条回答
  •  春和景丽
    2020-12-13 08:09

    static int getIndex(int A[], int B[]) {
        int start = -1;
        int N = A.length;
        for (int i = 0; i < N; i++) {
            int c = A[i] - B[i];
            if (c >= 0) {
                int j = i + 1;
                while (c >= 0 && j < i + N) {
                    c += A[j % N] - B[j % N];
                    j++;
                }
                if (c >= 0) {
                    start = i;
                    break;
                }
            }
        }
        return start;
    }
    

提交回复
热议问题