Greedy Algorithms8 sections · 316 units
Open in Course

Problem - Gas Station

Circular route

Gas stations on a circular route. Station i has gas[i] fuel and costs cost[i] to reach the next station. Find the starting station to complete the circuit, or return 1-1 if impossible.

Example: gas = [1,2,3,4,5], cost = [3,4,5,1,2]. Start at station 33 (00-indexed). Can you complete the circuit? What is the greedy approach? Constraint: n104n \le 10^4. Simulating every start is O(n2)O(n^2) time using O(1)O(1) space. Greedy gives O(n)O(n).