forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0646-maximum-length-of-pair-chain.kt
64 lines (53 loc) · 1.55 KB
/
0646-maximum-length-of-pair-chain.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//greedy algorithm O(nlogn)
class Solution {
fun findLongestChain(_pairs: Array<IntArray>): Int {
val pairs = _pairs.sortedWith(compareBy({ it[1] }, { it[0] }))
var res = 1
var time = pairs[0][1]
for (i in 1 until pairs.size) {
if(pairs[i][0] > time) {
res++
time = pairs[i][1]
}
}
return res
}
}
//dp O(n^2)
class Solution {
fun findLongestChain(_pairs: Array<IntArray>): Int {
val pairs = _pairs.sortedWith(compareBy({ it[0] }, { it[1] }))
val n = pairs.size
val dp = IntArray(n) { 1 }
for (i in 0 until n) {
for (j in 0 until n) {
if (pairs[i][0] > pairs[j][1]) {
dp[i] = maxOf(dp[i], dp[j] + 1)
}
}
}
return dp[n - 1]
}
}
//recursion + memoization O(n^2)
class Solution {
fun findLongestChain(_pairs: Array<IntArray>): Int {
val pairs = _pairs.sortedWith(compareBy({ it[0] }, { it[1] }))
val dp = IntArray (pairs.size) { -1 }
fun dfs(i: Int): Int {
if (i == pairs.size) return 0
if (dp[i] != -1) return dp[i]
var res = 1
for (j in 0 until i) {
if (pairs[i][0] > pairs[j][1])
res = maxOf(res, dfs(j) + 1)
}
dp[i] = res
return res
}
var res = 1
for (i in 0 until pairs.size)
res = maxOf(res, dfs(i))
return res
}
}