




Sponsored
Sponsored
This approach leverages the greedy paradigm. The main idea is to iterate over the stations while keeping track of the total gas and total cost. Additionally, we maintain a running sum (which is the cumulative balance of gas at each station) and a start index. If the running sum ever becomes negative, it implies that the current segment of the journey is infeasible. Thus, we reset the running sum and choose the next station as the candidate for the starting point. Finally, if the total gas is greater than or equal to the total cost, the last chosen candidate is the valid starting point.
Time Complexity: O(n), where n is the number of stations.
Space Complexity: O(1), as extra space used is constant.
1using System;
2
3class Program {
4    public static int CanCompleteCircuit(int[] gas, int[] cost) {
5        int totalGas = 0, totalCost = 0, start = 0, currentGas = 0;
6
7        for (int i = 0; i < gas.Length; i++) {
8            totalGas += gas[i];
9            totalCost += cost[i];
10            currentGas += gas[i] - cost[i];
11
12            if (currentGas < 0) {
13                start = i + 1;
14                currentGas = 0;
15            }
16        }
17
18        return totalGas >= totalCost ? start : -1;
19    }
20
21    static void Main(string[] args) {
22        int[] gas = {1, 2, 3, 4, 5};
23        int[] cost = {3, 4, 5, 1, 2};
24        int result = CanCompleteCircuit(gas, cost);
25        Console.WriteLine(result);
26    }
27}
28The C# solution is direct, using variables to track total gas, total costs, and the current gas balance. If the current gas becomes negative, reset the candidate starting index for a possible circular journey to the next station. After the iterations, it returns the starting index if the total gas is no less than the total cost, otherwise returns -1.
This approach attempts to simulate the journey starting from each station. For each potential start, check if the car can complete the circuit using the available gas at each station. While this approach may be easier to understand, it is inefficient because it checks each station iteratively, leading to potentially high computational costs for longer arrays. It is not recommended for larger datasets but can be useful for understanding how the journey works preliminarily.
Time Complexity: O(n^2) due to double iteration.
Space Complexity: O(1) as no extra space is utilized.
1
This brute force method checks every gas station as a candidate for starting point. It uses the variable currentGas to simulate the journey to verify whether each one can be completed in a circle. If at any point the gas becomes insufficient, the loop breaks early, and the next station is checked as a potential start.