Skip to content

Commit c3599ce

Browse files
authoredAug 8, 2022
2022-08-08 update: added "Longest Increasing Subsequence" (#62)
1 parent 010b5da commit c3599ce

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
// https://leetcode.com/problems/longest-increasing-subsequence/
7+
public class LongestIncreasingSubsequence {
8+
9+
private final List<Integer> incr = new ArrayList<>();
10+
private final int[] input;
11+
12+
public LongestIncreasingSubsequence(int[] input) {
13+
this.input = input;
14+
}
15+
16+
public int solution() {
17+
incr.add(input[0]);
18+
for (int i = 1; i < input.length; i++) {
19+
int num = input[i];
20+
if (num > incr.get(incr.size() - 1)) {
21+
incr.add(num);
22+
} else {
23+
incr.set(binarySearch(num), num);
24+
}
25+
}
26+
return incr.size();
27+
}
28+
29+
private int binarySearch(int num) {
30+
int l = 0;
31+
int r = incr.size() - 1;
32+
while (l <= r) {
33+
int m = (l + r) / 2;
34+
if (incr.get(m) == num) {
35+
return m;
36+
}
37+
if (incr.get(m) < num) {
38+
l = m + 1;
39+
} else {
40+
r = m - 1;
41+
}
42+
}
43+
return l;
44+
}
45+
46+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertEquals;
6+
7+
public class LongestIncreasingSubsequenceTest {
8+
9+
@Test
10+
public void defaultTest() {
11+
assertEquals(
12+
4,
13+
new LongestIncreasingSubsequence(
14+
new int[]{10, 9, 2, 5, 3, 7, 101, 18}
15+
).solution()
16+
);
17+
}
18+
19+
}

0 commit comments

Comments
 (0)
Please sign in to comment.