- 첫λ²μ§Έ index
0
λΆν° μμν΄μ λ§μ½ tankμ κΈ°λ¦μ΄ 0λ³΄λ€ μμμ§λ©΄ λ€μ μμΉλ₯Ό μλ‘μ΄ μμμ μΌλ‘ νμ¬ νμνλ€.
count
λ₯Ό μ¬μ©νμ¬ λͺ¨λ stationμ λ°©λ¬Ένλμ§ κΈ°λ‘νλ€.
start
μ λ²μκ° array sizeλ₯Ό λμ΄κ°κ² λλ©΄ μμμ μ μ°Ύμ§ λͺ»νκ² λλ―λ‘ νμμ μ’
λ£νλ€.
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start = 0;
int pos = 0;
int tank = 0;
int count = 0;
while (count < gas.size() and start < gas.size()) {
int index = pos % gas.size();
tank += gas[index] - cost[index];
if (tank < 0) {
start = ++pos;
tank = count = 0;
} else {
++pos;
++count;
}
}
return count == gas.size()? start : -1;
}
};