/**
*环形路上有n个加油站,第i个加油站的汽油量是gas[i].
* 你有一辆车,车的油箱能够无限装汽油。从加油站i走到下一个加油站(i+1)花费的油量是cost[i],你从一个加油站出发,刚开始的时候油箱里面没有汽油。
* 求从哪一个加油站出发能够在环形路上走一圈。返回加油站的下标,若是没有答案的话返回-1。
* 注意:
* 答案保证惟一。
*
*/
public class Main56 {
public static void main(String[] args) {
int[] gas = {41,42,3,4,45};
int[] cost = {1,2,63,64,5};
System.out.println(Main56.canCompleteCircuit(gas, cost));
}
public static int canCompleteCircuit(int[] gas, int[] cost) {
int[] rest = new int[gas.length];
for (int i=0;i<gas.length;i++) {
rest[i] = gas[i] - cost[i];
}
int index = 0;
int total = 0;
for (int i=0;i<rest.length;i++) {
total = total + rest[i];
if (rest[i] < 0) {
index = i+1;
}
}
return total >= 0 ? index : -1;
}
}