Skip to content

Commit c636ff2

Browse files
committed
feat : lis
1 parent 057821e commit c636ff2

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
input : array of integers
3+
output : length of the longest strictly increasing subsequence;
4+
example
5+
0 1 0 3 2 3 > 0 1 2 3 >> length : 4
6+
4 3 2 1 > 1 >> length : 1
7+
1 1 1 1 > 1 >> length : 1
8+
9+
constraints :
10+
1) empty array allowed?
11+
no, at least one
12+
13+
solution 1) brute force
14+
nested for loop
15+
iterate through the array from index i = 0 to n-1 when n is the lenght of input
16+
iterate throught the array from index j = i + 1 to n
17+
update current Maximum value
18+
if bigger than prev max value count ++
19+
tc : O(n^2);
20+
sc : O(1)
21+
22+
solution 2) binary search + dp
23+
iterate through the array
24+
search from saved values.
25+
if current value is bigger than everything add
26+
else change value
27+
28+
let val[i] save the smallest value of length i subsequence
29+
tc : O(nlogn)
30+
sc : O(n)
31+
32+
*/
33+
34+
class Solution {
35+
public int lengthOfLIS(int[] nums) {
36+
List<Integer> vals = new ArrayList<>();
37+
for(int num : nums) {
38+
if(vals.isEmpty() || vals.getLast() < num) {
39+
vals.add(num);
40+
} else {
41+
vals.set(binarySearch(vals, num), num);
42+
}
43+
}
44+
return vals.size();
45+
}
46+
int binarySearch(List<Integer> vals, int num) {
47+
int l = 0, r = vals.size()-1;
48+
while(l <= r) {
49+
int mid = (r - l) / 2+ l;
50+
if(vals.get(mid) == num) {
51+
return mid;
52+
} else if (vals.get(mid) > num) {
53+
r = mid - 1;
54+
} else {
55+
l = mid + 1;
56+
}
57+
}
58+
return l;
59+
}
60+
}

0 commit comments

Comments
 (0)