From 479ea893d0250cf0d8996fb092de49e99297c00e Mon Sep 17 00:00:00 2001 From: Namisha Goyal <44649227+namigoel@users.noreply.github.com> Date: Fri, 30 Oct 2020 03:06:48 +0530 Subject: [PATCH] Create LongestPalindromicSubsequence.cpp --- .../LongestPalindromicSubsequence.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Dynamic Programming/LongestPalindromicSubsequence.cpp diff --git a/Dynamic Programming/LongestPalindromicSubsequence.cpp b/Dynamic Programming/LongestPalindromicSubsequence.cpp new file mode 100644 index 0000000..d032f44 --- /dev/null +++ b/Dynamic Programming/LongestPalindromicSubsequence.cpp @@ -0,0 +1,33 @@ + +#include +using namespace std; + + +int max (int x, int y) { return (x > y)? x : y; } + + +int lps(char *seq, int i, int j) +{ +if (i == j) + return 1; + + +if (seq[i] == seq[j] && i + 1 == j) + return 2; + + +if (seq[i] == seq[j]) + return lps (seq, i+1, j-1) + 2; + +return max( lps(seq, i, j-1), lps(seq, i+1, j) ); +} + + +int main() +{ + char seq[] = "HACKTOBERFEST"; + int n = strlen(seq); + cout << "The length of the LPS is " + << lps(seq, 0, n-1); + return 0; +}