-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestIncreasingSubsequence.java
More file actions
63 lines (62 loc) · 2.1 KB
/
LongestIncreasingSubsequence.java
File metadata and controls
63 lines (62 loc) · 2.1 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
63
import java.util.Scanner;
/*
* @author Shaon Bhatta Shuvo
*/
public class LongestIncreasingSubsequence {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Array length: ");
int arrayLength = input.nextInt();
int a[] = new int[arrayLength];
System.out.print("Insert array elements: ");
for (int i = 0; i < arrayLength; i++) {
a[i]=input.nextInt();
}
longestIncreasingSubsequence(a);
}
public static void longestIncreasingSubsequence(int a[]){
//lis will provide the longest common subesequece length
int lis[]=new int[a.length];
//trace array will help us to trace the the sequence
int trace[]=new int[a.length];
//initializing lis array with value 1
for (int i = 0; i < lis.length; i++) {
lis[i]=1;
}
//initializing trace with value -1, values -1 means it has no previous element
for (int i = 0; i < trace.length; i++) {
trace[i]=-1;
}
//updating the lis array to get the lis value
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < i; j++) {
if(a[i]>a[j] && lis[i]<lis[j]+1){
lis[i]=lis[j]+1;
trace[i]=j;
}
}
}
//maximus value of lis array is the value we are looking for
int max =lis[0], index=0;
for (int i = 1; i < lis.length; i++) {
if(max<lis[i]){
max=lis[i];
index=i;
}
}
System.out.print("\nLength of LIS="+max);
//System.out.println("index"+index);
System.out.print("\nSequece:");
printSequence(a,trace,index);
}
//method for printing the sequence
public static void printSequence(int a[],int trace[],int index){
if(trace[index]==-1) {
System.out.println(a[index]+" ");
return;
}
index=trace[index];
printSequence(a,trace,index);
System.out.print(a[index]+ " ");
}
}