The problem is to determine if there is a starting gas station around a circular route where a car can travel, starting with an empty tank. The car can travel from the index i
to the next index i+1
, and the car’s tank can be refueled at each gas station. You are given two integer arrays: gas
where gas[i]
is the amount of gas at the i-th
station, and cost
where cost[i]
is the amount of gas needed to travel from the i-th
station to the (i+1)-th
station.
Your goal is to return the starting gas station index if you can travel around the circuit once in the clockwise direction, otherwise, return -1.
Example 1:
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Example 2:
Input: gas = [2,3,4], cost = [3,4,3]
Output: -1
Q: Can the arrays gas
and cost
have different lengths?
A: No, both arrays will always have the same length.
Q: What are the constraints on the values of gas[i]
and cost[i]
?
A: We assume that 0 <= gas[i], cost[i] <= 10^4
and the lengths of the arrays are 1 <= n <= 10^4
.
Q: If there are multiple valid starting stations, can I return any of them? A: Yes, you can return any valid starting station index.
#include <vector>
using namespace std;
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int totalGas = 0, totalCost = 0, start = 0, tank = 0;
for (int i = 0; i < n; ++i) {
totalGas += gas[i];
totalCost += cost[i];
tank += gas[i] - cost[i];
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return totalGas >= totalCost ? start : -1;
}
};
This approach ensures an efficient solution through optimized traversal and logical condition checks, adhering to a linear time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?