Greedy Algorithms8 sections · 316 units
Open in Course

Gas Station - The Idea

Find the valley

Two insights:

1.1. If total gas >= total cost, a solution exists.

2.2. If you run out of gas at station j starting from i, no station between i and j can be the answer. Greedy approach: track running sum of (gas - cost). When it goes negative, reset start to the next station. The last reset point is the answer. Without insight 22, you would restart from every failed position, wasting time.