[Leetcode] [JAVA] Gas station

Source: Internet
Author: User

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 of gas to travel from station cost[i] 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.


You can treat two arrays as an array, benifit[i]=gas[i]-cost[i] is the oil that is obtained for each section of the road.

Two principles: 1. If the total benifit is negative, it will not finish in any way.

2. If the oil runs out from a petrol station I, to the section of the gas station J, it will run out of oil at any petrol station between I,j and J or J.

Based on the above two principles, need a variable total statistic benifit, need a subscript start Mark start station, initial 0, need a variable tank record tank. Once the tank is found to be less than 0 at an I point in the process, the start Mark is i+1, which means that the gas station from the previous start to I cannot be used as the starting gas station.

Finally, see if total is less than 0. return-1 If yes, or start.

Code:

1  Public intCancompletecircuit (int[] Gas,int[] cost) {2         intTank = 0;3         intStart = 0;4         intTotal = 0;5          for(inti=0;i<gas.length;i++)6         {7Total + = gas[i]-Cost[i];8Tank + = gas[i]-Cost[i];9             if(tank<0)Ten             { OneStart = I+1; ATank=0; -             } -         } the         returnTotal>=0?start:-1; -}

[Leetcode][java] gas station

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.