[Leetcode] Gas station

Source: Internet
Author: User

gas Station

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.

Ideas:

Start at the No. 0 point and traverse the container. Use a variable remain to record the amount of oil remaining in the mailbox after each point. If the remain<0 of point I is computed, it cannot be drawn from point I, because the next point cannot be reached. Then only the starting point can be re-selected. (This starting point must not be at a certain point between the previous beginning and the I point.) It can be proved that, assuming the previous starting point is T, point I remain<0, there is a point J between T and I, then T arrives at the time of the J Remain>=0, and if the starting point is set at J Point, there is remain=0, so to point I will still have remain <0. )

So the topic is simplified, not all points are used as a starting point to traverse. If remain<0 is found at point I, then the next starting point is i+1, until it is able to cycle one lap or the starting point is greater than the capacity of a given container.

Exercises

classSolution { Public:    intCancompletecircuit (vector<int> &gas, vector<int> &Cost ) {        intStart =0; intremain =0; intn =gas.size (); intI=0;  while(Start<n && i<start+N) {if(i<N) remain= remain+gas[i]-Cost[i]; Elseremain= remain+gas[i-n]-cost[i-N]; if(remain<0) {Start= i+1; Remain=0; } I++; }        if(start>=N)return-1; returnstart; }};
View Code

[Leetcode] 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.