Gas Station(Can Circuit) #leetcode #nterview #leetcodequestionandanswers

preview_player
Показать описание
Question: Gas Station

There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.

Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique

Approach: Greedy Approach

Iterate through the gas stations, tracking the total gas available and the gas remaining after travelling to the next station. If the remaining gas becomes negative, update the potential starting station and reset the remaining gas. If the total gas available is non-negative at the end, return the potential starting station; otherwise, it returns -1 to indicate an impossible solution.

Time Complexity: O(n)

Space Complexity: O(1)

#softwareengineer #dsa #interviewpreparation
Рекомендации по теме
visit shbcf.ru