-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCS.java
More file actions
62 lines (45 loc) · 1.37 KB
/
LCS.java
File metadata and controls
62 lines (45 loc) · 1.37 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.ArrayList;
import java.util.Arrays;
class LCS{
static int longestIncreasingSubsequence(int arr[], int n){
int[] dp=new int[n];
Arrays.fill(dp,1);
int[] hash=new int[n];
Arrays.fill(hash,1);
for(int i=0; i<=n-1; i++){
hash[i] = i; // initializing with current index
for(int prev_index = 0; prev_index <=i-1; prev_index ++){
if(arr[prev_index]<arr[i] && 1 + dp[prev_index] > dp[i]){
dp[i] = 1 + dp[prev_index];
hash[i] = prev_index;
}
}
}
int ans = -1;
int lastIndex =-1;
for(int i=0; i<=n-1; i++){
if(dp[i]> ans){
ans = dp[i];
lastIndex = i;
}
}
ArrayList<Integer> temp=new ArrayList<>();
temp.add(arr[lastIndex]);
while(hash[lastIndex] != lastIndex){ // till not reach the initialization value
lastIndex = hash[lastIndex];
temp.add(arr[lastIndex]);
}
// reverse the array
System.out.print("The subsequence elements are ");
for(int i=temp.size()-1; i>=0; i--){
System.out.print(temp.get(i)+" ");
}
System.out.println();
return ans;
}
public static void main(String args[]) {
int arr[] = {10,9,2,5,3,7,101,18};
int n = arr.length;
longestIncreasingSubsequence(arr,n);
}
}