Gas Station(LeetCode)
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.
题目理解:N个加油站,形成一个环路,每个加油站i到i+1的耗油量为cost[i],每个加油站可以补充的油量为gas[i]。求该环路中的一个起点,使得能够汽车能跑完全程。
举个例子:gas{1, 2, 4, 3, 0, 7} cost{4, 0, 2, 3, 5, 6}
从站i到达下一站能够贡献的剩余油量为 gas[i]-cost[i], remain{-3, 2, 2, 0, –5, 7},明显从剩余量为7的加油站开始,能够跑完整圈。
分析待续。。
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int sz = gas.size();
if(sz==0) return -1;
int i,j;
for(i = 0; i < sz; ++i)
gas[i]-=cost[i];
int sum = 0;
for(i = 0; i < sz; ++i){
gas.push_back(gas[i]);
sum+= gas[i];
}
if(sum < 0) return -1;
int newSize = gas.size();
vector<int> dp(newSize);
vector<int> from(newSize);
dp[0] = gas[0];
from[0] = 0;
int maxi = 0;
for(i = 1; i < newSize-1; ++i)
{
if(dp[i-1]<0){
dp[i] = gas[i];
from[i] = i;
}else{
dp[i] = dp[i-1]+gas[i];
from[i] = from[i-1];
}
if(dp[maxi] < dp[i]) maxi = i;
}
return from[maxi];
}
};
浙公网安备 33010602011771号