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:
parent
2e5cb675cd
commit
fb1d1ea6f9
1 changed files with 38 additions and 0 deletions
38
kt/maximum-number-of-moves-in-a-grid.kt
Normal file
38
kt/maximum-number-of-moves-in-a-grid.kt
Normal 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]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue