Gas station Solution

Source: Internet
Author: User

Problem

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.

Solution

Key to the solution is a conclusion:

If sum of gas >= sum of costs, then there must exists one or more solution.

If sum of Gas < sum of costs, then there is no solution.

So we can use the method of exclusion here.

We need also note here is if a can not reach C in a the sequence of a-->b-->c and then B can does not make it either.

1  Public classSolution {2      Public intCancompletecircuit (int[] Gas,int[] cost) {3         if(Gas = =NULL|| Cost = =NULL)4             return-1;5         if(Gas.length! =cost.length)6             return-1;7         intStart = 0;8         intsumremaining = 0;9         inttotalremaining = 0;Ten          for(inti = 0; i < gas.length; i++) { One             intTMP = Gas[i]-Cost[i]; A             if(sumremaining >= 0) { -Sumremaining + =tmp; -}Else { theStart =i; -Sumremaining =tmp; -             } -Totalremaining + =tmp; +         } -         if(Totalremaining < 0) +             return-1; A         returnstart; at     } -}

Gas station Solution

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.