Skip to content

134. Gas Station 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
    const int gasSum = accumulate(gas.begin(), gas.end(), 0);
    const int costSum = accumulate(cost.begin(), cost.end(), 0);
    if (gasSum - costSum < 0)
      return -1;

    int ans = 0;
    int sum = 0;

    // Try to start from each index.
    for (int i = 0; i < gas.size(); ++i) {
      sum += gas[i] - cost[i];
      if (sum < 0) {
        sum = 0;
        ans = i + 1;  // Start from the next index.
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int canCompleteCircuit(int[] gas, int[] cost) {
    final int gasSum = Arrays.stream(gas).sum();
    final int costSum = Arrays.stream(cost).sum();
    if (gasSum - costSum < 0)
      return -1;

    int ans = 0;
    int sum = 0;

    // Try to start from each index.
    for (int i = 0; i < gas.length; ++i) {
      sum += gas[i] - cost[i];
      if (sum < 0) {
        sum = 0;
        ans = i + 1; // Start from the next index.
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def canCompleteCircuit(self, gas: list[int], cost: list[int]) -> int:
    ans = 0
    net = 0
    summ = 0

    # Try to start from each index.
    for i in range(len(gas)):
      net += gas[i] - cost[i]
      summ += gas[i] - cost[i]
      if summ < 0:
        summ = 0
        ans = i + 1  # Start from the next index.

    return -1 if net < 0 else ans