kt: add «300. Longest Increasing Subsequence»

URL:	https://leetcode.com/problems/longest-increasing-subsequence/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-06 22:18:48 +01:00
parent 734cb7d959
commit 1ca11ef95b
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,26 @@
class Solution {
fun lengthOfLIS(nums: IntArray): Int =
when (nums.size) {
0 -> 0
1 -> 1
else -> {
val dp = IntArray(nums.size) { 1 }
nums.indices
.asSequence()
.drop(1)
.flatMap { i ->
(0..i - 1).asSequence().map { j -> i to j }
}
.maxOf { (i, j) ->
when {
nums[i] <= nums[j] -> 1
else -> {
dp[i] = listOf(dp[i], 1 + dp[j]).max()
dp[i]
}
}
}
}
}
}