Longest Increasing Subsequence | Practice | GeeksforGeeks

Given an array of integers, find the length of the longest (strictly) increasing subsequence from the given array.
Example 1:
Input:
N = 16
A[]={0,8,4,12,2,10,6,14,1,9,5
     13,3,11,7,15}
Output: 6
Explanation:Longest increasing subsequence
0 2 6 9 13 15, which has length 6

Example 2:
Input:
N = 6
A[] = {5,8,3,7,9,1}
Output: 3
Explanation:Longest increasing subsequence
5 7 9, with length 3
Your Task:
Complete the function longestSubsequence() which takes the input array and its size as input parameters and returns the length of the longest increasing subsequence.
Expected Time Complexity : O( N*log(N) )
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 105
0 ≤ A[i] ≤ 106
0
nitinkaplas906434 days ago
void helper(int val,vector<int>&v)   {       int low=0;       int high=v.size()-1;       while(low<high)       {           int mid=(low+high)/2;           if(v[mid]>val)           high=mid;           else           low=mid+1;       }       v[low]=val;          }   int longestSubsequence(int n, int a[])   {      vector<int>v;      v.push_back(a[0]);            for(int i=1;i<n;i++)      {          if(a[i]>v.back())          v.push_back(a[i]);          else          helper(a[i],v);      }      return v.size();   }
0
pranavkhandare45456 days ago
Java solution
 static int longestSubsequence(int size, int a[])   {       // code here       int[] dp = new int[size];       int omax=0;       for(int i=0;i<size;i++){           int max=0;           for(int j=0;j<i;j++){               if(a[j]<a[i]){                   if(dp[j]>max){                       max=dp[j];                   }               }           }           dp[i]=max+1;           if(dp[i]>omax){               omax=dp[i];           }       }       return omax;
0
shishir17pandey1 week ago
 int longestSubsequence(int n, int a[])   {      // your code here      int dp[n+1];      int maxi=0;      for(int i=0;i<n;i++){          dp[i]=1;      }      for(int i=0;i<n;i++){          for(int j=0;j<i;j++){              if(a[i]>a[j] && dp[i]<dp[j]+1){                  dp[i]=dp[j]+1;              }          }      }      for(int i=0;i<n;i++){          if(maxi<dp[i]){              maxi=dp[i];          }      }      return maxi;   }};
0
sarthakiet20192 weeks ago
int longestSubsequence(int n, int a[])   {      // your code here                        vector<int>ans;            for(int i=0;i<n;++i){          auto it=lower_bound(ans.begin(),ans.end(),a[i]);                    if(it==ans.end())          ans.push_back(a[i]);                    else          *it=a[i];      }            return ans.size();   }simple cpp solution
0
achakraborty04102 weeks ago
Using Java
static int longestSubsequence(int size, int a[])   {       int ans=0;      int t[]=new int[size];      Arrays.fill(t,1);      for(int i=0;i<size;i++){          for(int j=0;j<i;j++)              if(a[i]>a[j])              t[i]=Math.max(t[i],1+t[j]);            ans=Math.max(ans,t[i]);      }      return ans;   }
0
ashagarwala30992 weeks ago
// dp approach-state of the index is that we store in each index the lis //length till that index  including that a[i] itself so when next element //comes we jst compare the a[i] values if it matches the condition we //include and like this we do for all prev indexes and store the max //length in our curr index comes to check 
class Solution{   public:   //Function to find length of longest increasing subsequence.   int longestSubsequence(int n, int a[])   {      // your code here         int dp[n];   dp[0]=1;      for(int i=1;i<n;i++)    {dp[i]=1;    for(int j=i-1;j>=0;j--)       {           if(a[i]>a[j])           dp[i]=max(dp[i],dp[j]+1);       }            }    int res=0;    for(int i=0;i<n;i++)       {           res=max(res,dp[i]);       }                  return res;               }};
+3
rainx2 weeks ago
People who are struggling to understand LIS(BINARY SEARCH nLogn Variant)
Let us first have a quick look in the code. No Youthoober explained like this
/* ITERATOR VERSION */

int longestSubsequence(int n, int a[]) {  
        vector<int> res;
        for(int i = 0; i < n; i++) {
            auto it=lower_bound(res.begin(), res.end(), a[i]);
            if(it==res.end()) {
                res.push_back(a[i]);
            } 
            else {
                *it=a[i];
            }
        }
        return res.size();
    }
/* INDEX VERSION */
int longestSubsequence(int n, int a[]) {
        vector<int> res;
        for(int i = 0; i < n; i++) {
            int index=lower_bound(res.begin(), res.end(), a[i])-res.begin();
            if(index==res.size()) {
                res.push_back(a[i]);
            } 
            else {
                res[index]=a[i];
            }
        }
        return res.size();
    }
First understand what LOWER BOUND does.
LOWER BOUND RETURNS THE INDEX/ITERATOR OF THE ELEMENT WHICH IS JUST GREATER THAN OR EQUAL TO ARR[i], Incase there is nothing like that, it returns the size of the vector/array /END OF ITERATOR.
Now, let us see how binary search is actually helping us to reduce the complexity, I hope you are familiar with the N*N approach since I would not be discussing that here.
 
Ok, the trick binary search is doing here is IT IS PLACING EVERY SINGLE ELEMENT IN ARR[i] TO ITS ORIGINAL PLACE IN THE IN-PROGESS LIS CONSTRUCTION.
 
Did not get it, well let us take a example
 
Let us say we have a LIS(in progress)={1,3,5};
Now since we are trying to place every single element of ARR[i] in its correct place in LIS, we binary search for ARR[i] and there can be TWO cases for it
 
After BINARY SEARCH we found an index where element is equal to or just greater than ARR[i], so what we do is place arr[i] in the element positionWe did not get any element in the building LIS, and therefore we need to append add it in LIS since there is no element greater than or equal to ARR[i] in LIS
After BINARY SEARCH we found an index where element is equal to or just greater than ARR[i], so what we do is place arr[i] in the element position
We did not get any element in the building LIS, and therefore we need to append add it in LIS since there is no element greater than or equal to ARR[i] in LIS
LIS(in progress)={1,3,5};
Let us say we encounter ARR[i]=4, we binary search for it in LIS, we get index of element 5, we place 4 in-place of 5 because it is its original place.
 
LIS becomes ={1,3,4};
 
Now pay attention closely and see how binary search is so cool in finding LIS effectively.
 
As we are proceeding in ARR, let us say we found ARR[i]=5, yeah the 5 we just removed and placed 4 in place of it. But this ARR[i]=5 is found while iterating forward. Can be said this is the duplicate of that 5 we found earlier, so we binary search for ARR[i]=5 in LIS and found that there is no element which is equal or greater than 5, so according to our condition we will append it to our LIS
 
LIS becomes={1,3,4,5}
 
See how placing 4 in place of 5 earlier helped us increasing LIS now. This is how binary search works actually, it is placing every single ARR[i] in its correct place in the building LIS
 
Thank you and ask question if you have. Do comment something so I know this is was helpful for yall
 Sapport for more such explainations
 
 
 
 
0
rainx
This comment was deleted.
0
moninmodi3 weeks ago
map<int,int> mp;       for(int i=0;i<n;i++)       mp[a[i]]++;       vector<int> v;       for(auto x:mp){           v.push_back(x.first);       }       sort(v.begin(),v.end());       int m=v.size();       int t[n+1][m+1];       for(int i=0;i<n+1;i++){           for(int j=0;j<m+1;j++){               if(i==0||j==0){                   t[i][j]=0;               }               else{                   if(a[i-1]==v[j-1]){                       t[i][j]=1+t[i-1][j-1];                   }                   else{                       t[i][j]=max(t[i-1][j],t[i][j-1]);                   }               }           }       }       return t[n][m];
+1
jainmuskan5653 weeks ago
 int lis_help(int prev,int curr,int a[],int n,vector<vector<int>> &dp){       if(curr==n){           return 0;       }       if(dp[prev+1][curr]!= -1){           return dp[prev+1][curr];       }       int len= lis_help(prev,curr+1,a,n,dp);       if(prev==-1 || a[prev]<a[curr]){           len= max(len,1+lis_help(curr,curr+1,a,n,dp));       }       return dp[prev+1][curr]= len;   }   int longestSubsequence(int n, int a[])   {       vector<vector<int>> dp(n,vector<int>(n+1,-1));       return lis_help(-1,0,a,n,dp);   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.