There was N gas stations along a circular route, where the amount of gas at station I was gas[i].
You had a car with an unlimited gas tank and it costs cost[i] of the gas-to-travel from station I to its next station (I+1). You begin the journey with a 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.
There are n petrol stations on the ring route, petrol at each petrol station gas[i], from each gas station to the next station consuming petrol cost[i], ask from which gas station to go back to the starting point, if neither can return-1 (note that the solution is unique).
Code
#include <iostream> #include <stdio.h> #include <vector> using namespace std; //Time complexity O (n), Space complexity O (1) class Solution {public: int cancompletecircuit (vector< int & Gt &gas, vector< int > &cost) { int total = 0; &n bsp; Int J =-1; for (int i = 0, sum = 0; i < gas.size (); ++i) { & nbsp; sum + = gas[i]-cost[i]; Total + = Gas[i]-cost[i]; if (Sum < 0) { & nbsp; j = i; sum = 0;