LeetCode-134 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.

Ideas:

1. Loop through each of the starting points to calculate whether the requirements are met. Time Complexity of O (n^2);

2. Assuming that the remaining amount of petrol is sufficient to travel from the i->j-1, the petrol is not sufficient to travel from J-1 to J, i.e. I cannot travel to J from the start.

At this point, according to the 1th way of thinking, is from I+1 as a new starting point to start the traversal.

But at the first petrol station there must be Gas[i] >= cost[i], the same can not be done from I+1 to J;

and Gas[i]+gas[i+1]-cost[i]-cost[i+1] >= 0, then from I+2 to J can not be completed;

And so on, all points between I and J cannot be fulfilled, and the traversal is started directly from j+1 as a new node.

When I to n satisfies the condition, it is necessary to determine whether the remaining oil amount of I to J is sufficient for 0 to i-1 distance.

The code is as follows:

 Public intCancompletecircuit (int[] Gas,int[] cost) {        intleft = 0;//Petrol remaining quantityintPass = 0;//gasoline shortage from 0->i-1intStart = 0;  for(inti=0; i<gas.length; i++) { left= Gas[i]-Cost[i] +Left ; if(Left < 0) {Pass= left +Pass; Start= i + 1; Left= 0; }        }        if(pass + left >= 0)            returnstart; Else             return-1; }

LeetCode-134 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.