Find the minimum, then you are done!


  • 5
    F
    class Solution {
    public:
        int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
            int loc = 0;
            int sum=0;
            int min=INT_MAX;
            //find the minimum 
            for(int i =0; i<gas.size(); ++i){
                sum+=gas[i]-cost[i];
                if(sum<min){
                    min = sum;
                    loc=i;
                }
            }
            
            if(sum>=0) return (loc+1)%gas.size();
            else return -1;
        }
    };

  • 0
    J

    This solution cannot be right.

    Imagine gas[foo]-cost[foo] is the only negative value, but you cannot start from foo.


  • 0
    J

    [2,0,3],[1,2,2] should produce 2

    this solution would've produced -1


Log in to reply
 

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