-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLPS.java
More file actions
58 lines (50 loc) · 1.46 KB
/
LPS.java
File metadata and controls
58 lines (50 loc) · 1.46 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
import java.util.Scanner;
public class LPS
{
public static int LCS(int[] seq, int[] rev, int n)
{
int[][] dp = new int[n + 1][n + 1];
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(seq[i - 1] == rev[j - 1])
{
dp[i][j] = 1+ dp[i - 1][j - 1];
}
else
{
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[n][n];
}
public static void main(String[] args)
{
int n;
Scanner data = new Scanner(System.in);
System.out.println("Enter the value of integer n: ");
n = data.nextInt();
if(1 <= n && n <= 100)
{
int[] seq = new int[n];
System.out.println("Enter the sequence: ");
for(int i = 0; i < n; i++)
{
seq[i] = data.nextInt();
}
int[] rev = new int[n];
for(int i = 0; i < n; i++)
{
rev[i] = seq[n - i - 1];
}
int lpsLength = LCS(seq, rev, n);
System.out.println("The length of the Longest Palindromic Subsequence is: " + lpsLength);
}
else
{
System.out.println("Value of n should be between 1 and 100.");
}
}
}