From 0b908404dea74a095cd2720f2b918f5330115289 Mon Sep 17 00:00:00 2001 From: MAINAK CHAUDHURI <64016811+MainakRepositor@users.noreply.github.com> Date: Sat, 5 Jun 2021 12:21:23 +0530 Subject: [PATCH] Create 476.cpp --- 476.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 476.cpp diff --git a/476.cpp b/476.cpp new file mode 100644 index 0000000..8fa4ce6 --- /dev/null +++ b/476.cpp @@ -0,0 +1,36 @@ +// C++ program of above approach +#include +using namespace std; + +// A utility function to get max of two integers +int max (int x, int y) { return (x > y)? x : y; } + +// Returns the length of the longest palindromic subsequence in seq +int lps(char *seq, int i, int j) +{ +// Base Case 1: If there is only 1 character +if (i == j) + return 1; + +// Base Case 2: If there are only 2 +// characters and both are same +if (seq[i] == seq[j] && i + 1 == j) + return 2; + +// If the first and last characters match +if (seq[i] == seq[j]) + return lps (seq, i+1, j-1) + 2; + +// If the first and last characters do not match +return max( lps(seq, i, j-1), lps(seq, i+1, j) ); +} + +/* Driver program to test above functions */ +int main() +{ + char seq[] = "GEEKSFORGEEKS"; + int n = strlen(seq); + cout << "The length of the LPS is " + << lps(seq, 0, n-1); + return 0; +}