Greedy
Local Choice Visualizer
Watch greedy strategies sort, scan, select, merge, and reset state while each step updates the current result and complexity.
O(n) time / O(1) space
result: start 0selected: 0
S0default
1/3
net -2
S1default
2/4
net -2
S2default
3/5
net -2
S3default
4/1
net 3
S4default
5/2
net 3
Result
start 0
Time
O(n)
Space
O(1)
Step Note
Track total balance and current tank.
function gasStation(gas: number[], cost: number[]) {
let start = 0
let tank = 0
let total = 0
for (let index = 0; index < gas.length; index++) {
const delta = gas[index] - cost[index]
tank += delta
total += delta
if (tank < 0) {
start = index + 1
tank = 0
}
}
return total >= 0 ? start : -1
}