File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments