题目:
代码(首刷看解析 2024年2月15日):
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int curSum = 0;
int sum = 0;
int startIndex = 0;
for (int i = 0; i < gas.size(); ++i) {
curSum += gas[i] - cost[i];
sum += gas[i] - cost[i];
if (curSum < 0) {
startIndex = i + 1;
curSum = 0;
}
}
if (sum < 0) return -1;
return startIndex;
}
};