From 96a6a9151f4e44e134f6394d76444a55ff4d4e7e Mon Sep 17 00:00:00 2001 From: Shubham Marathe <76870563+shubhammarathe15@users.noreply.github.com> Date: Sat, 29 Oct 2022 00:38:14 +0530 Subject: [PATCH] Create Longest Increasing subsequence --- Longest Increasing subsequence | 40 ++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Longest Increasing subsequence diff --git a/Longest Increasing subsequence b/Longest Increasing subsequence new file mode 100644 index 0000000..f66fba7 --- /dev/null +++ b/Longest Increasing subsequence @@ -0,0 +1,40 @@ + +#include +#include +using namespace std; + + +int f(int idx, int prev_idx, int n, int a[], + vector >& dp) +{ + if (idx == n) { + return 0; + } + + if (dp[idx][prev_idx + 1] != -1) { + return dp[idx][prev_idx + 1]; + } + + int notTake = 0 + f(idx + 1, prev_idx, n, a, dp); + int take = INT_MIN; + if (prev_idx == -1 || a[idx] > a[prev_idx]) { + take = 1 + f(idx + 1, idx, n, a, dp); + } + + return dp[idx][prev_idx + 1] = max(take, notTake); +} + +int longestSubsequence(int n, int a[]) +{ + vector > dp(n + 1, vector(n + 1, -1)); + return f(0, -1, n, a, dp); +} + + +int main() +{ + int a[] = { 3, 10, 2, 1, 20 }; + int n = sizeof(a) / sizeof(a[0]); + cout << "Length of lis is " << longestSubsequence(n, a); + return 0; +}