Simple c++ solution


  • 1
    J
    class Solution {
    public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
    	int startPos = 0;
    	while (startPos < gas.size())
    	{
    		int curGas = 0;
    		int curPos = startPos;
    		while (curGas >= 0)
    		{
    			curGas = curGas + gas[curPos] - cost[curPos];
    			curPos = (curPos + 1) % gas.size();
    			if (curGas >= 0 && curPos == startPos)
    				return startPos;
    		}
    
    		if (curPos <= startPos)
    			return -1;
    
    		startPos = curPos;
    	}
    
    	return -1;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.