1
+ package com .interview .array ;
2
+
3
+ import java .util .Arrays ;
4
+
5
+ public class LongestIncreasingSubSequenceOlogNMethod {
6
+
7
+ /**
8
+ * Returns index in T for ceiling of s
9
+ */
10
+ private int ceilIndex (int input [], int T [], int end , int s ){
11
+ int start = 0 ;
12
+ int middle ;
13
+ int len = end ;
14
+ while (start <= end ){
15
+ middle = (start + end )/2 ;
16
+ if (middle < len && input [T [middle ]] < s && s <= input [T [middle +1 ]]){
17
+ return middle +1 ;
18
+ }else if (input [T [middle ]] < s ){
19
+ start = middle +1 ;
20
+ }else {
21
+ end = middle -1 ;
22
+ }
23
+ }
24
+ return -1 ;
25
+ }
26
+
27
+ public int longestIncreasingSubSequence (int input []){
28
+ int T [] = new int [input .length ];
29
+ int R [] = new int [input .length ];
30
+ for (int i =0 ; i < R .length ; i ++) {
31
+ R [i ] = -1 ;
32
+ }
33
+ T [0 ] = 0 ;
34
+ int len = 0 ;
35
+ for (int i =1 ; i < input .length ; i ++){
36
+ if (input [T [0 ]] > input [i ]){ //if input[i] is less than 0th value of T then replace it there.
37
+ T [0 ] = i ;
38
+ }else if (input [T [len ]] < input [i ]){ //if input[i] is greater than last value of T then append it in T
39
+ len ++;
40
+ T [len ] = i ;
41
+ R [T [len ]] = T [len -1 ];
42
+ }else { //do a binary search to find ceiling of input[i] and put it there.
43
+ int index = ceilIndex (input , T , len ,input [i ]);
44
+ T [index ] = i ;
45
+ R [T [index ]] = T [index -1 ];
46
+ }
47
+ }
48
+
49
+ //this prints increasing subsequence in reverse order.
50
+ System .out .print ("Longest increasing subsequence " );
51
+ int index = T [len ];
52
+ while (index != -1 ) {
53
+ System .out .print (input [index ] + " " );
54
+ index = R [index ];
55
+ }
56
+
57
+ System .out .println ();
58
+ return len +1 ;
59
+ }
60
+
61
+ public static void main (String args []){
62
+ //int input[] = {2,5,3,1,2,10,6,7,8};
63
+ int input [] = {3 , 4 , -1 , 5 , 8 , 2 , 3 , 12 , 7 , 9 , 10 };
64
+ LongestIncreasingSubSequenceOlogNMethod lis = new LongestIncreasingSubSequenceOlogNMethod ();
65
+ System .out .println ("Maximum length " + lis .longestIncreasingSubSequence (input ));
66
+ }
67
+ }
0 commit comments