没有想出来,查阅后发现题目思路很巧妙,详见:http://www.programcreek.com/2014/03/leetcode-gas-station-java/
美中不足的是fact1的证明网上很少或者说不是很流畅,但是自己也写不出好的证明
后经CMU高人指点:假设S(i)为从0到i的partial sum of diff array (diff array为gas array - cost array之差),找到i使得S(i)为最小,则i+1为最终答案(如果总和>0)此结果可通过partial sum curve得出。
i右边的curve会提高|S[i]|,i左边的curve会提升final height - S[i]。因为S[i]为最小,所以curve右侧必定均>=0。左边的最低点为S[i],提升final height - S[i]后为final height。故若原final heght >0 则左边curve均>0。事实上,以任意i作为可能答案,i右边的curve都会升高|S[i]|,而左边的curve提高final hegiht - S[i],故此当S[i]最小时,curve提升的最多。
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int size = gas.size();
int currentSum = 0;
int currentStartingPoint = 0;
int total = 0;
for (int i = 0; i < size; ++i)
{
if (currentSum < 0)
{
currentStartingPoint = i;
currentSum = 0;
}
currentSum += gas[i] - cost[i];
total += currentSum;
}
if (total >= 0)
return currentStartingPoint;
else
return -1;
}
};