Lintcode-medium-gas Station

Source: Internet
Author: User
Tags lintcode

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 I to its cost[i] 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.

Given gas 4 stations gas[i]=[1,1,3,1] with, and the cost[i]=[2,2,1,1] . The starting gas station's index is 2 .

 Public classSolution {/**     * @paramgas:an array of integers *@paramcost:an array of integers *@return: An integer*/     Public intCancompletecircuit (int[] Gas,int[] cost) {        //Write your code here                if(Gas = =NULL|| Gas.length = = 0 | | Cost = =NULL|| Cost.length = = 0 | | Gas.length! =cost.length)return-1; intGas_sum = 0; intCost_sum = 0;  for(inti = 0; i < gas.length; i++) Gas_sum+=Gas[i];  for(inti = 0; i < cost.length; i++) Cost_sum+=Cost[i]; if(Gas_sum <cost_sum)return-1; intleft = 0; intStart = 0;  while(Start <gas.length) {            inti =start;  for(; i < gas.length; i++) { left+=Gas[i]; Left-=Cost[i]; if(Left < 0) { left= 0;  Break; }            }                        if(I! =gas.length) Start= i + 1; Else                returnstart; }                return-1; }}

Lintcode-medium-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.