From 56cfa976490cfd618e5e5b49ea233a6952291ec0 Mon Sep 17 00:00:00 2001 From: Prakarsh Singh Date: Tue, 9 Jan 2024 17:38:07 +0530 Subject: [PATCH] FIX #1276 Added to the Dynamic programming folder in cpp --- .../Longest-Increasing-Subsequence.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 algorithms/CPlusPlus/Dynamic-Programming/Longest-Increasing-Subsequence.cpp diff --git a/algorithms/CPlusPlus/Dynamic-Programming/Longest-Increasing-Subsequence.cpp b/algorithms/CPlusPlus/Dynamic-Programming/Longest-Increasing-Subsequence.cpp new file mode 100644 index 000000000..16643550d --- /dev/null +++ b/algorithms/CPlusPlus/Dynamic-Programming/Longest-Increasing-Subsequence.cpp @@ -0,0 +1,35 @@ +//We are given an array arr[] , we have to find the longest increasing subsequecne , +//Subsequence is descirbed as all elements of the subsequence are in increaseing order +// ex. arr[]=[4,6,2,8] lis= 3 (4,6,8) +//brute force: generate all the subsequence and return the longest such subsequence +//time complexity . 2^n +//optimal approach is Dynamic Programming time complexity O(N*N) where N is the lenght of the array +//space complexity is O(N*N)+O(N) +// code.. + +#include +using namespace std; + +int solve(int arr[], int n, int ind, int prev,vector>&dp){ + if(ind==n){ + return 0; + } + if(dp[ind][prev+1]!=-1)return dp[ind][prev+1]; + int nottake=0+solve(arr,n,ind+1,prev,dp); + int take=0; + if(prev==-1||arr[ind]>arr[prev]){ + take=1+solve(arr,n,ind+1,ind,dp); + } + return dp[ind][prev+1]=max(nottake,take); + +} +int lis(int arr[],int n){ + vector>dp(n,vector(n+1,-1)); + return solve(arr,n,0,-1,dp); +} +int main(){ + int arr[]={11,24,9,4,0,22,29}; + int n=sizeof(arr)/sizeof(arr[0]); + cout<<"the length of longest increase subsequence is "<