From 91b451fdfa40d34eefb4217ddfb448c9768475d6 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 31 Oct 2024 23:38:41 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB2463.=20Minimum=20Total=20Dis?= =?UTF-8?q?tance=20Traveled=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/minimum-total-distance-traveled/ --- kt/minimum-total-distance-traveled.kt | 45 +++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 kt/minimum-total-distance-traveled.kt diff --git a/kt/minimum-total-distance-traveled.kt b/kt/minimum-total-distance-traveled.kt new file mode 100644 index 0000000..dc569e7 --- /dev/null +++ b/kt/minimum-total-distance-traveled.kt @@ -0,0 +1,45 @@ +class Solution { + fun product( + xs: Sequence, + ys: Sequence, + ): Sequence> = xs.flatMap { x -> ys.map { y -> x to y } } + + fun product( + xs: Iterable, + ys: Iterable, + ): Sequence> = product(xs.asSequence(), ys.asSequence()) + + private fun abs(x: Int): Int = listOf(-x, x).max() + + private data class Factory(val position: Int, var limit: Int) + + fun minimumTotalDistance( + robot: List, + factory: Array, + ): Long { + val robots = robot.sorted() + val repairs = + factory.map { it -> + Factory(it[0], it[1]) + }.sortedBy { + it.position + }.flatMap { + (1..it.limit).map { _ -> it.position } + } + + val dp = Array(1 + robots.size) { LongArray(1 + repairs.size) } + // Base + robots.indices.forEach { i -> + dp[i][repairs.size] = 1L.shl(40) + } + + product(robots.indices.reversed(), repairs.indices.reversed()).forEach { (i, j) -> + val assigning = abs(robots[i] - repairs[j]) + dp[i + 1][j + 1] + val skipping = dp[i][j + 1] + + dp[i][j] = listOf(assigning, skipping).min() + } + + return dp[0][0] + } +}