From fef6742a2f5ced5bfd7b319952fe48f19e38b348 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 20 Aug 2022 18:30:43 +0200 Subject: [PATCH] =?UTF-8?q?problems:=20add=20=E2=80=9E871.=20Minimum=20Num?= =?UTF-8?q?ber=20of=20Refueling=20Stops=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/minimum-number-of-refueling-stops.kt | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 problems/minimum-number-of-refueling-stops.kt diff --git a/problems/minimum-number-of-refueling-stops.kt b/problems/minimum-number-of-refueling-stops.kt new file mode 100644 index 0000000..8d2625f --- /dev/null +++ b/problems/minimum-number-of-refueling-stops.kt @@ -0,0 +1,59 @@ +import java.util.PriorityQueue + +class Solution { + fun minRefuelStops(target: Int, startFuel: Int, stations: Array): Int { + var maxReach = startFuel + val availableRefuelling = PriorityQueue(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 + ) +}