MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / gasStations

Function gasStations

kotlin/Greedy/GasStations.kt:1–22  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1fun gasStations(gas: List<Int>, cost: List<Int>): Int {
2 // If the total gas is less than the total cost, completing the
3 // circuit is impossible.
4 if (gas.sum() < cost.sum()) {
5 return -1
6 }
7 var start = 0
8 var tank = 0
9 for (i in 0 until gas.size) {
10 tank += gas[i] - cost[i]
11 // If our tank has negative gas, we cannot continue through the
12 // circuit from the current start point, nor from any station
13 // before or including the current station 'i'.
14 if (tank < 0) {
15 // Set the next station as the new start point and reset the
16 // tank.
17 start = i + 1
18 tank = 0
19 }
20 }
21 return start
22}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected