LeetCode Solutions

134. Gas Station

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
    const int gasses = accumulate(begin(gas), end(gas), 0);
    const int costs = accumulate(begin(cost), end(cost), 0);
    if (gasses - costs < 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 next index
      }
    }

    return ans;
  }
};
			

class Solution {
  public int canCompleteCircuit(int[] gas, int[] cost) {
    final int gasses = Arrays.stream(gas).sum();
    final int costs = Arrays.stream(cost).sum();
    if (gasses - costs < 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 next index
      }
    }

    return ans;
  }
}
			

class Solution:
  def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
    ans = 0
    net = 0
    summ = 0

    for i in range(len(gas)):
      net += gas[i] - cost[i]
      summ += gas[i] - cost[i]
      if summ < 0:
        summ = 0
        ans = i + 1

    return -1 if net < 0 else ans