14. Gas Station
β GFG solution to the Gas Station problem: find the starting station to complete a circular tour using greedy approach with optimal time and space complexity. π
π§© Problem Description
π Examples
Example 1
Input: gas[] = [4, 5, 7, 4], cost[] = [6, 6, 3, 5]
Output: 2
Explanation: Start at station 2 with 7 units of gas. Tank = 0 + 7 = 7
Travel to station 3: Available gas = (7 - 3 + 4) = 8
Travel to station 0: Available gas = (8 - 5 + 4) = 7
Travel to station 1: Available gas = (7 - 6 + 5) = 6
Return to station 2: Available gas = (6 - 6) = 0Example 2
Input: gas[] = [3, 9], cost[] = [7, 6]
Output: -1
Explanation: No starting station allows completing the circular tour.
Total gas = 3 + 9 = 12, Total cost = 7 + 6 = 13. Since total cost > total gas,
it's impossible to complete the tour.π Constraints
β
My Approach
Greedy Single-Pass Algorithm
Why This Works:
π Time and Auxiliary Space Complexity
π§βπ» Code (C++)
π§βπ» Code (Java)
π Code (Python)
π§ Contribution and Support
πVisitor Count
Last updated