The fifth week of algorithm class 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 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 is guaranteed to be unique.

There are n petrol stations on the ring route, petrol at each petrol station gas[i], from each gas station to the next station consuming petrol cost[i], ask from which gas station to go back to the starting point, if neither can return-1 (note that the solution is unique).

Code

#include <iostream> #include <stdio.h> #include <vector> using namespace std;  //Time complexity O (n), Space complexity O (1) class Solution {public:      int cancompletecircuit (vector< int & Gt &gas, vector< int > &cost) {         int total = 0;   &n bsp;      Int J =-1;          for (int i = 0, sum = 0; i < gas.size (); ++i) {   & nbsp;         sum + = gas[i]-cost[i];              Total + = Gas[i]-cost[i];              if (Sum < 0) {    & nbsp;            j = i;                  sum = 0;

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.