class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int n = gas.size();
int curSum = 0;
int total = 0;
int pos = 0;
for(int i = 0; i < n; ++i)
{
int curRemain = gas[i]-cost[i];
if(curSum >= 0) curSum += curRemain;
else curSum = curRemain, pos = i;
total += curRemain;
}
return total >= 0 ? pos: -1;
}
};
[LeetCode]Gas Station
最新推荐文章于 2023-05-29 15:50:15 发布