problems: add „871. Minimum Number of Refueling Stops“
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
6eb2f09892
commit
fef6742a2f
1 changed files with 59 additions and 0 deletions
59
problems/minimum-number-of-refueling-stops.kt
Normal file
59
problems/minimum-number-of-refueling-stops.kt
Normal 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
|
||||||
|
)
|
||||||
|
}
|
Loading…
Reference in a new issue