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:
parent
734cb7d959
commit
1ca11ef95b
1 changed files with 26 additions and 0 deletions
26
kt/longest-increasing-subsequence.kt
Normal file
26
kt/longest-increasing-subsequence.kt
Normal 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]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue