kt: add «2684. Maximum Number of Moves in a Grid»

URL:	https://leetcode.com/problems/maximum-number-of-moves-in-a-grid/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-10-29 23:36:45 +01:00
parent 2e5cb675cd
commit fb1d1ea6f9
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,38 @@
class Solution {
fun <A, B> product(
xs: Sequence<A>,
ys: Sequence<B>,
): Sequence<Pair<A, B>> = xs.flatMap { x -> ys.map { y -> x to y } }
fun <A, B, C> product(
xs: Sequence<A>,
ys: Sequence<B>,
zs: Sequence<C>,
): Sequence<Triple<A, B, C>> = xs.flatMap { x -> ys.flatMap { y -> zs.map { z -> Triple(x, y, z) } } }
fun <A, B> product(
xs: Iterable<A>,
ys: Iterable<B>,
): Sequence<Pair<A, B>> = product(xs.asSequence(), ys.asSequence())
fun <A, B, C> product(
xs: Iterable<A>,
ys: Iterable<B>,
zs: Iterable<C>,
): Sequence<Triple<A, B, C>> = product(xs.asSequence(), ys.asSequence(), zs.asSequence())
fun maxMoves(grid: Array<IntArray>): 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]
}
}
}