Gas Station

by atalaykutlay

Solution to "Gas Station" on Leetcode.

Gas Station
1class Solution:
2    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
3        if (sum(gas) - sum(cost) < 0):
4            return -1
5
6        tank = 0
7        start_index = 0
8        for i in range(len(gas)):
9            tank += gas[i] - cost[i]
10            if tank < 0:
11                start_index = i+1
12                tank = 0
13
14        return start_index
15

✨ Code Explanation ✨

This code solves the "Gas Station" problem, which involves finding the starting gas station that can complete a circular route without running out of gas. The code defines a class named "Solution" with a method called "canCompleteCircuit". This method takes in two lists as parameters: "gas" and "cost", representing the amount of gas at each gas station and the cost to travel from one station to the next. The code first checks if the total amount of gas minus the total cost is negative. If it is, it means that there is not enough gas to complete the circuit, so it returns -1. Next, the code initializes a variable called "tank" to keep track of the current amount of gas in the tank, and a variable called "start_index" to keep track of the starting gas station. The code then iterates through each gas station using a for loop. At each iteration, it updates the tank by adding the amount of gas at the current station and subtracting the cost for traveling to the next station. If the tank becomes negative, it means that the current gas station cannot be the starting point, so the code sets the start_index to the current station's index + 1 and resets the tank to 0. Finally, the code returns the start_index, which represents the gas station from which the circular route can be completed without running out of gas.

Share

Share
Video
A cool 10 sec video.
Share
Detailed
Title, description, and syntax highlighted code.
Share
Simple
Syntax highlighted code with gradient background colored presentation.

Comments

It looks like there is no comment for this snippet. Leave the first one!
You need to login to send a comment.

Similar Snippets

Count Number of Texts
Count Number of Texts

Solution to "Count Number of Texts" question on Leetcode.

Language: python12 months ago
Quicksort in Python
Quicksort in Python

An easy quicksort implementation in Python.

Language: python13 months ago
Second Minimum Node In a Binary Tree
Second Minimum Node In a Binary Tree

Solution to "Second Minimum Node In a Binary Tree" on Leetcode.

Language: python11 months ago