Skip to content

Commit 562333a

Browse files
authored
Create 0646-maximum-length-of-pair-chain.kt
1 parent d164ce1 commit 562333a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//greedy algorithm O(nlogn)
2+
class Solution {
3+
fun findLongestChain(_pairs: Array<IntArray>): Int {
4+
val pairs = _pairs.sortedWith(compareBy({ it[1] }, { it[0] }))
5+
6+
var res = 1
7+
var time = pairs[0][1]
8+
for (i in 1 until pairs.size) {
9+
if(pairs[i][0] > time) {
10+
res++
11+
time = pairs[i][1]
12+
}
13+
}
14+
15+
return res
16+
}
17+
}
18+
19+
//dp O(n^2)
20+
class Solution {
21+
fun findLongestChain(_pairs: Array<IntArray>): Int {
22+
val pairs = _pairs.sortedWith(compareBy({ it[0] }, { it[1] }))
23+
val n = pairs.size
24+
val dp = IntArray(n) { 1 }
25+
26+
for (i in 0 until n) {
27+
for (j in 0 until n) {
28+
if (pairs[i][0] > pairs[j][1]) {
29+
dp[i] = maxOf(dp[i], dp[j] + 1)
30+
}
31+
}
32+
}
33+
34+
return dp[n - 1]
35+
}
36+
}

0 commit comments

Comments
 (0)