[Leetcode 134] Gas station

Source: Internet
Author: User

Title Link: 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 cost[i] of the gas-to-travel from station 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 I s guaranteed to is unique. * */public class Gasstation {//16/16 test Cases passed.//status:accepted//runtime:247 ms//submitted:0 minutes ago//Time    Complexity o (n) space complexity O (1) public int cancompletecircuit (int[] gas, int[] cost) {int remaining = 0;//The amount of oil remaining from the start point to the current point int begin = -1;//start point subscript int total = 0;//Determine if there is a solution for (int i = 0; i < cost.length; i++) {remaining + = Gas[i]-    Cost[i];      Total + = Gas[i]-cost[i];if (remaining < 0) {remaining = 0;begin = i;}} Return (Total < 0)?    -1:begin + 1; public static void Main (string[] args) {}}


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