62 lines
1.7 KiB
Kotlin
62 lines
1.7 KiB
Kotlin
import java.util.PriorityQueue
|
|
|
|
class Solution {
|
|
fun minRefuelStops(
|
|
target: Int,
|
|
startFuel: Int,
|
|
stations: Array<IntArray>,
|
|
): Int {
|
|
var maxReach = startFuel
|
|
val availableRefuelling = PriorityQueue<Int>(reverseOrder())
|
|
|
|
var refuelled = 0
|
|
var i = 0
|
|
|
|
while (maxReach < target) {
|
|
while (i < stations.size && stations[i][0] <= maxReach) {
|
|
// keep track of possible refuels
|
|
availableRefuelling.add(stations[i][1])
|
|
i++
|
|
}
|
|
|
|
if (availableRefuelling.isEmpty()) {
|
|
// no refuels are available and target has not been reached
|
|
return -1
|
|
}
|
|
|
|
// refuel at least once in order to progress
|
|
maxReach += availableRefuelling.poll()!!
|
|
refuelled++
|
|
}
|
|
return refuelled
|
|
}
|
|
}
|
|
|
|
fun main() {
|
|
val s = Solution()
|
|
|
|
check(s.minRefuelStops(1, 1, arrayOf()) == 0)
|
|
check(s.minRefuelStops(100, 1, arrayOf(intArrayOf(10, 100))) == -1)
|
|
check(
|
|
s.minRefuelStops(
|
|
100, 10, arrayOf(intArrayOf(10, 60), intArrayOf(20, 30), intArrayOf(30, 30), intArrayOf(60, 40)),
|
|
) == 2,
|
|
)
|
|
check(
|
|
s.minRefuelStops(
|
|
1000, 299,
|
|
arrayOf(
|
|
intArrayOf(13, 21),
|
|
intArrayOf(26, 115),
|
|
intArrayOf(100, 47),
|
|
intArrayOf(225, 99),
|
|
intArrayOf(299, 141),
|
|
intArrayOf(444, 198),
|
|
intArrayOf(608, 190),
|
|
intArrayOf(636, 157),
|
|
intArrayOf(647, 255),
|
|
intArrayOf(841, 123),
|
|
),
|
|
) == 4,
|
|
)
|
|
}
|