MCPcopy Create free account
hub / github.com/Vishruth-S/CompetitiveCode / Solution

Class Solution

LeetCode_problems/Gas Station/solution.cpp:26–54  ·  view source on GitHub ↗

LOGIC: =================================================================================================== 1. We maintain two variables `surplus`, `deficit`, `start`. `surplus` - The amount of gas in tank for travelling to next station. `deficit` - The amount of gas that we are in shortfall. `start` - The potential starting station for the tour. 2. At anytime the current amount of gas `surp

Source from the content-addressed store, hash-verified

24===================================================================================================
25*/
26class Solution {
27public:
28 int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
29
30 int n = gas.size();
31
32 // Step - 1
33 int surplus = 0, deficit = 0, start = 0;
34
35 for(int i = 0; i < n; ++i){
36
37 surplus += (gas[i] - cost[i]);
38
39 // Step - 2
40 if(surplus < 0){
41 deficit -= surplus;
42 surplus = 0;
43 start = i + 1;
44 }
45 }
46
47 // Step - 3 (a)
48 if(surplus < deficit)
49 return -1;
50
51 // Step - 3 (b)
52 return start;
53 }
54};

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected