![]() |
VOOZH | about |
Given two arrays gas[] and cost[], each gas station i provides gas[i] fuel, and it takes cost[i] fuel to travel to the next station. Starting with an empty tank, find the index of the gas station from which you can complete a full circular tour. If itβs not possible, return -1.
Note: If a solution exists, it is guaranteed to be unique.
Examples:
Input: gas[] = [4, 5, 7, 4], cost[] = [6, 6, 3, 5]
Output: 2
Explanation: Start at gas station at index 2 and fill up with 7 units of gas. Your 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) = 0.
Therefore, 2 is the starting index.Input: gas[] = [3, 9], cost[] = [7, 6]
Output: -1
Explanation: There is no gas station to start with such that you can complete the tour.
Table of Content
The simplest approach is to consider each index as a starting point and check if a car can complete the circular tour starting from that index. If we find a valid starting point, we will return it.
2
The idea is maintain the available gas while traversing. If it ever drops below zero at station i, the journey cannot start from the current starting point, so we shift the starting point to i + 1.
How it Works?
Note: If starting from index s fails at station i (available gas < 0), then no station between s and i can be a valid start either because each of them would reach station i with even less gas than starting at s. Therefore, the next possible candidate is i + 1.
2
This approach is an optimization of the previous one. After completing a full traversal of the array, instead of checking validity by circularly traversing from the starting index, we calculate the total remaining gas (the net difference between gas and cost). If this difference is greater than or equal to zero, the starting point is valid; otherwise, completing a circular loop is not possible.
2