From fb1d1ea6f9ec402e940e25905e8c69ab08fb4ba0 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 29 Oct 2024 23:36:45 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB2684.=20Maximum=20Number=20of?= =?UTF-8?q?=20Moves=20in=20a=20Grid=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/maximum-number-of-moves-in-a-grid/ Signed-off-by: Matej Focko --- kt/maximum-number-of-moves-in-a-grid.kt | 38 +++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 kt/maximum-number-of-moves-in-a-grid.kt diff --git a/kt/maximum-number-of-moves-in-a-grid.kt b/kt/maximum-number-of-moves-in-a-grid.kt new file mode 100644 index 0000000..fd74798 --- /dev/null +++ b/kt/maximum-number-of-moves-in-a-grid.kt @@ -0,0 +1,38 @@ +class Solution { + fun product( + xs: Sequence, + ys: Sequence, + ): Sequence> = xs.flatMap { x -> ys.map { y -> x to y } } + + fun product( + xs: Sequence, + ys: Sequence, + zs: Sequence, + ): Sequence> = xs.flatMap { x -> ys.flatMap { y -> zs.map { z -> Triple(x, y, z) } } } + + fun product( + xs: Iterable, + ys: Iterable, + ): Sequence> = product(xs.asSequence(), ys.asSequence()) + + fun product( + xs: Iterable, + ys: Iterable, + zs: Iterable, + ): Sequence> = product(xs.asSequence(), ys.asSequence(), zs.asSequence()) + + fun maxMoves(grid: Array): Int { + val dp = Array(grid.size) { IntArray(grid[0].size) } + + product(grid[0].indices.reversed().drop(1), grid.indices, -1..1).filter { + (x, y, dy) -> + y + dy >= 0 && y + dy < dp.size && grid[y][x] < grid[y + dy][x + 1] + }.forEach { (x, y, dy) -> + dp[y][x] = listOf(dp[y][x], 1 + dp[y + dy][x + 1]).max() + } + + return dp.indices.maxOf { y -> + dp[y][0] + } + } +}