-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest Increasing Subsequence.java
More file actions
36 lines (32 loc) · 999 Bytes
/
Longest Increasing Subsequence.java
File metadata and controls
36 lines (32 loc) · 999 Bytes
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
//https://practice.geeksforgeeks.org/problems/longest-increasing-subsequence-1587115620/1
class Solution
{
//Function to find length of longest increasing subsequence.
static int longestSubsequence(int size, int a[])
{
// code here
ArrayList<Integer> list = new ArrayList<>();
list.add(a[0]);
for(int i=1; i<size; i++) {
int n = list.size();
if(a[i] > list.get(n-1)) list.add(a[i]);
else {
int index = binarySearch(list, a[i], 0, n-1);
list.set(index, a[i]);
}
}
return list.size();
}
static int binarySearch(ArrayList<Integer> list, int a, int left, int right) {
while( right > left) {
int mid = (left + right)/2;
if(list.get(mid) >= a) {
right = mid;
}
else {
left = mid+1;
}
}
return right;
}
}