-
Notifications
You must be signed in to change notification settings - Fork 360
/
Longest_Common_Subsequence
47 lines (37 loc) · 1.12 KB
/
Longest_Common_Subsequence
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
import java.util.ArrayList;
import java.util.*;
public class solution {
public static ArrayList<Integer> longestSubsequence(int[] arr){
// Write your code here
HashMap<Integer,Integer> h=new HashMap<>();
ArrayList<Integer> ans=new ArrayList<>();
int small=arr[0];
int largest=arr[0];
for (int i = 0; i <arr.length ; i++) {
int tempsmall=arr[i];
int tempLarge=arr[i];
int k=1;
while(h.containsKey(arr[i]+k))
{
tempLarge=arr[i]+k;
k++;
}
k=1;
while(h.containsKey(arr[i]-k))
{
tempsmall=arr[i]-k;
k++;
}if(!h.containsKey(arr[i]))
h.put(arr[i],i );
if(tempLarge-tempsmall>largest-small||(tempLarge-tempsmall==largest-small&&h.get(tempsmall)<h.get(small)))
{
largest=tempLarge;
small=tempsmall;
}
}
for (int i = small; i <=largest ; i++) {
ans.add(i);
}
return ans;
}
}