There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to
its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
非常经典的一道题。可以转换成求最大连续和做,但是有更简单的方法。基于一个数学定理:
如果一个数组的总和非负,那么一定可以找到一个起始位置,从他开始绕数组一圈,累加和一直都是非负的
(证明貌似不难,以后有时间再补)
有了这个定理,判断到底是否存在这样的解非常容易,只需要把全部的油耗情况计算出来看看是否大于等于0即可。
那么如何求开始位置在哪?
注意到这样一个现象:
1. 假如从位置i开始,i+1,i+2...,一路开过来一路油箱都没有空。说明什么?说明从i到i+1,i+2,...肯定是正积累。
2. 现在突然发现开往位置j时油箱空了。这说明什么?说明从位置i开始没法走完全程(废话)。那么,我们要从位置i+1开始重新尝试吗?不需要!为什么?因为前面已经知道,位置i肯定是正积累,那么,如果从位置i+1开始走更加没法走完全程了,因为没有位置i的正积累了。同理,也不用从i+2,i+3,...开始尝试。所以我们可以放心地从位置j+1开始尝试。
Proof of "if total gas is greater than total cost, there is a solution":
Let i be the index such that the the partial sum
gas[0]-cost[0]+gas[1]-cost[1]+...+gas[i]-cost[i]
is the smallest, then the start position should be start=i+1 ( start=0 if i=n-1)
因为从这个位置开始,不会出现负值,因为start是最小的,如果出现后面又出现负的,那start就不是最小的
到结尾的时候已经是正到最大值(因为从0到i是负的最大值),从结尾调到开始位置再走也不会出现小于0的情况,因为可以保证最大的正比最大的负要大(不是说全部的和大于0嘛)
结论:主要全部加起来大于0,就一定有解,然后他说,The solution is guaranteed to be unique,那就说明只有上面说的那个keypoint 满足条件而且解就是那个keypoint
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int total = 0, sum = 0, start = 0;
for(int i=0; i<gas.length; i++) {
// all sum up
total += gas[i] - cost[i];
// if current sum is less than 0, then start from next node
if(sum < 0) {
start = i;
sum = gas[i] - cost[i];
} else {
sum += gas[i] - cost[i];
}
}
return total >= 0 ? start : -1;
}
}
2刷
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sum = 0;
int min = gas[0], start = 0;
for(int i=0; i<gas.length; i++) {
sum += gas[i] - cost[i];
if(sum < min) {
min = sum;
start = i + 1;
}
}
return sum<0 ? -1 : start % gas.length;
}
}
本文探讨了一种经典的算法问题——环形路线上的加油站问题。通过分析加油站提供的油量与消耗成本之间的关系,提出了一种高效的解决方案,确保车辆能绕环形路线一周而油箱始终保持非负状态。

317

被折叠的 条评论
为什么被折叠?



