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] + } +}