problems: add „871. Minimum Number of Refueling Stops“

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-08-20 18:30:43 +02:00
parent 6eb2f09892
commit fef6742a2f
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,59 @@
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
)
}