forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLIS.java
More file actions
56 lines (47 loc) · 1.28 KB
/
LIS.java
File metadata and controls
56 lines (47 loc) · 1.28 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
/*Time complexity O(nlogn) */
import java.util.*;
public class LIS{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(); //No. of elements
int[] ar=new int[n];
for(int i=0;i<n;i++) {
ar[i]=sc.nextInt();
}
int result=lengthOfLIS(ar);
System.out.println(result);
}
public static int lengthOfLIS(int[] nums)
{
// Base case
if(nums.length <= 1)
return nums.length;
// This will be our array to track longest sequence length
int T[] = new int[nums.length];
// Fill each position with value 1 in the array
for(int i=0; i < nums.length; i++)
T[i] = 1;
// Mark one pointer at i. For each i, start from j=0.
for(int i=1; i < nums.length; i++)
{
for(int j=0; j < i; j++)
{
// It means next number contributes to increasing sequence.
if(nums[j] < nums[i])
{
// But increase the value only if it results in a larger value of the sequence than T[i]
// It is possible that T[i] already has larger value from some previous j'th iteration
if(T[j] + 1 > T[i])
{
T[i] = T[j] + 1;
}
}
}
}
// Find the maximum length from the array that we just generated
int longest = 0;
for(int i=0; i < T.length; i++)
longest = Math.max(longest, T[i]);
return longest;
}
}