Skip to content

Commit 9265fe3

Browse files
committed
Add longest increasing subsequence solution
1 parent 45f9d49 commit 9265fe3

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
fun lengthOfLIS(nums: IntArray): Int {
3+
val tails = mutableListOf<Int>()
4+
5+
for (num in nums) {
6+
val pos = binarySearchLeftmost(tails, num)
7+
8+
if (pos == tails.size) {
9+
tails.add(num)
10+
} else {
11+
tails[pos] = num
12+
}
13+
}
14+
15+
return tails.size
16+
}
17+
18+
fun binarySearchLeftmost(list: List<Int>, target: Int): Int {
19+
var left = 0
20+
var right = list.size
21+
22+
while (left < right) {
23+
val mid = left + (right - left) / 2
24+
if (list[mid] < target) {
25+
left = mid + 1
26+
} else {
27+
right = mid
28+
}
29+
}
30+
31+
return left
32+
}
33+
}

0 commit comments

Comments
 (0)