在一个环上有n个加油站,已知第i个加油站可以提供ai的油量,从第i个加油站到第i+1个加油站需要消耗bi的油量。(当i为n时,则表示n到1的油量)
问:是否能从某个加油站出发,绕环一圈回到这个加油站?(当途中到达某个加油站时的油量小于0则不可)。
public static void main(String[] args) { int[] gas = {4,2, 3, 1}; int[] cost = {1,3, 1, 2}; System.out.println(canCompleteCircuit2(gas, cost)); } /** * @param gas=[4,2,3,1] * @param cost=[1,3,1,2] * @return */ public static int canCompleteCircuit2(int[] gas, int[] cost) { int[] gasDouble = new int[gas.length * 2]; for (int i = 0; i < gasDouble.length; i++) { if (i < gas.length) { gasDouble[i] = gas[i]; } else { gasDouble[i] = gas[i - gas.length]; } } int[] costDouble = new int[cost.length * 2]; for (int i = 0; i < costDouble.length; i++) { if (i < cost.length) { costDouble[i] = cost[i]; } else { costDouble[i] = cost[i - cost.length]; } } for (int i = 0; i < gasDouble.length; i++) { boolean flag = true; int left = 0; for (int j = i; j < i + gas.length; j++) { left += gasDouble[j]; if (left < costDouble[i]) { flag = false; break; } left -= costDouble[i]; } if (flag) { return i; } } return -1; }
算法参考:https://www.cnblogs.com/andyqsmart/p/5460020.html