-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.kt
More file actions
43 lines (35 loc) · 1.06 KB
/
Solution.kt
File metadata and controls
43 lines (35 loc) · 1.06 KB
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
package problems.longestIncreasingSubsequence
import readmeGeneration.ProblemDifficulty
import readmeGeneration.ProblemSolution
@ProblemSolution(300, "Longest Increasing Subsequence", ProblemDifficulty.MEDIUM,
"https://leetcode.com/problems/longest-increasing-subsequence/")
class Solution {
fun lengthOfLIS(nums: IntArray): Int {
val seq = mutableListOf<Int>()
seq.add(nums[0])
for (n in nums.drop(1)) {
if (n > seq.last()) {
seq.add(n)
} else {
val swapIdx = binarySearch(seq, n)
seq[swapIdx] = n
}
}
return seq.size
}
private fun binarySearch(nums: List<Int>, n: Int): Int {
var low = 0
var high = nums.lastIndex
while (low < high) {
val mid = low + (high - low) / 2
if (nums[mid] == n) {
return mid
} else if (n > nums[mid]) {
low = mid + 1
} else {
high = mid
}
}
return low
}
}