Gas station [Leetcode] two solutions

Source: Internet
Author: User

Because the total gas is greater than the total cost of time. You will be able to circle the whole city.

First Solution :

If there is enough oil at the beginning. Departure from position I. The remaining amount of oil at position K is L (i,k).

to the random K. L (i,k) According to the difference of I, only the difference constant.

We just need to find the smallest L (0, K) corresponding to the k,k+1 to be asked.

The code is as follows:

    int Cancompletecircuit (vector<int> &gas, vector<int> &cost) {        int start = 0;        int Curgas = 0, Mingas = 0, Totalgas = 0;        for (int i = 0; i < gas.size (); i++)        {            int temp = gas[i]-cost[i];            Curgas + = temp;            Totalgas + = temp;            if (Mingas > Curgas)            {                start = i + 1;                Mingas = Curgas;            }        }        if (totalgas >= 0) return start% gas.size ();        else return-1;    }

Another solution:

Assuming L (I,k) < 0, the entire position between I and K is not to K

So from the location of the k+1 from 0 to start looking for

    int Cancompletecircuit (vector<int> &gas, vector<int> &cost) {        int start = 0;        int Curgas = 0, Totalgas = 0;        for (int i = 0; i < gas.size (); i++)        {            int temp = gas[i]-cost[i];            Curgas + = temp;            Totalgas + = temp;            if (Curgas < 0)            {                start = i + 1;                Curgas = 0;            }        }        if (totalgas >= 0) return start% gas.size ();        else return-1;    }


Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Gas station [Leetcode] two solutions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.