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
+1
shiva109010 hours ago
		int n = nums.size(), ans = INT_MIN;
        vector<int>dp(n, 1);
        for(int i = 0; i < n; i++){
            for(int j = 0; j < i; j++)
                if(nums[i] > nums[j]) dp[i] = max(dp[i], 1+dp[j]);
            ans = max(ans, dp[i]);
        }
        return ans;
+1
ankitdhopate15 hours ago
Java Solution
O(n log n) Time Complexity
O(n) Space Complexity
 
class Solution {   //Function to find length of longest increasing subsequence.   // O(n log n) Time complexity and O(n) Space Complexity   static int longestSubsequence(int n, int arr[]) {       if (n == 1)           return 1;                  // dp's current index would represent the maximum size       // and the value assigned to the index will be the last element of that index size array       int dp[] = new int[n + 1];
       // Initially fill all values to Integer max value except for 1st ind       // Whoes value will be Integer min       Arrays.fill(dp, Integer.MAX_VALUE);       dp[0] = Integer.MIN_VALUE;
       // Now iterate thorugh given array       for (int i = 0; i < n; i++) {                      // Now find the index value in dp such that it is just greater than the current arr[i]           int binS = Arrays.binarySearch(dp, arr[i]);           int index;           // If index element not found so do upper bound operation           if (binS < 0) {               index = Math.abs(binS) - 1;           }           // else direct index will be found           else {               index = binS;           }           if (arr[i] > dp[index - 1] && arr[i] < dp[index]) {               dp[index] = arr[i];           }       }
       int maxAns = 0;
       // Iterate from last index of dp to get maximum value       // The place where value of dp index is other than Integer max is the ans        for (int i = n; i > 0; i--) {           if (dp[i] != Integer.MAX_VALUE) {               maxAns = i;               break;           }       }
       return maxAns;   }} 
0
kumarjhaashish0082 days ago
C++ iterative solution
In O(n) time using lower_bound() function: Approach is binary search
 
class Solution{   public:   //Function to find length of longest increasing subsequence.   int longestSubsequence(int n, int a[])   {      // your code here      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          {              int it = lower_bound(v.begin(),v.end(),a[i])-v.begin();              v[it] = a[i];          }      }      return v.size();   }};
0
udhayashan12 days ago
#Recursion
#User function Template for python3

class Solution:
    
    #Function to find length of longest increasing subsequence.
    def longestSubsequence(self,A,n):
        # code here
        
        import sys
        dp = {}
        import functools
        @functools.lru_cache(None)
        def dfs(k1,prev):
            if k1 >= len(A):
                return 0
            
            if prev == -1:
                y1 = dfs(k1+1,prev)
                y2 = dfs(k1+1,A[k1])+1
                dp[(k1,prev)] = max(y1,y2)
            else:
                if A[k1] > prev:
                    y1 = dfs(k1+1,prev)
                    y2 = dfs(k1+1,A[k1])+1
                    dp[(k1,prev)] = max(y1,y2)
                else:
                    y1 = dfs(k1+1,prev)
                    dp[(k1,prev)] = y1
            return dp[(k1,prev)]
        
        return(dfs(0,-1))
    

       


#{ 
#  Driver Code Starts
#Initial Template for Python 3

if __name__ == '__main__':
    for _ in range(int(input())):
        n = int(input())
        a = [ int(x) for x in input().split() ]
        ob=Solution()
        print(ob.longestSubsequence(a,n))
# } Driver Code Ends
0
udhayashan1
This comment was deleted.
+1
bhavyakawatra62 days ago
// o( N logN) - Dynamic Programming + Binary Search 
class Solution{   public:   //Function to find length of longest increasing subsequence.   int longestSubsequence(int n, int a[])   {       // dp[i]-> longest inc subsequnce of length i.       // if there are multiple such sequnce themn we will take the sequnce that ends in the smallest element.       int im=1e6+5;       vector<int>dp(n+1,im);       dp[0]=-1;       for(int i=0;i<n;i++){           int indx=upper_bound(dp.begin(),dp.end(),a[i])-dp.begin();           if(dp[indx-1]!=a[i]){               dp[indx]=min(dp[indx],a[i]);           }       }      int m=1;      for(int i=0;i<=n;i++){          if(dp[i]<im)m=i;      }      return m;   }}; 
+1
bhavyakawatra62 days ago
// o(n2) approach class Solution{   public:   //Function to find length of longest increasing subsequence.   int longestSubsequence(int n, int a[])   {      // dp[i] is the longest inc subs. of indx i       vector<int>dp(n+1,1);      for(int i=0;i<n;i++){          for(int j=0;j<i;j++){              if(a[j]<a[i])                   dp[i]=max(dp[i],dp[j]+1);          }      }      int m=1;      for(int i=0;i<n;i++){          m=max(m,dp[i]);      }      return m;   }};
0
koolavi163 days ago
[class Solution:   def recur(self, arr, n, dp):       # print(n)       if n == 0:           return 1       if n in dp.keys():           return dp[n]       dp[n] = 1       for i in range(n-1, -1, -1):           if arr[n] > arr[i]:               dp[n] = max(dp[n],1 + self.recur(arr, i, dp))       return dp[n]
   def lengthOfLIS(self, Arr):       # code here       dp = {}       maxi = -1       for i in range(len(Arr)-1, -1, -1):           maxi = max(maxi, self.recur(Arr, i, dp))           print(dp)       # print(dp)       return maxi]
0
ayuak20004 days ago
int longestSubsequence(int n, int arr[])   {       vector<int>dp(n);       dp[0]=1;       for(int i=1;i<n;i++)       {           int maxm=0;           for(int j=0;j<i;j++)           {               if(arr[i]>arr[j])               {                   maxm=max(maxm,dp[j]);               }           }           dp[i]=maxm+1;       }       int ans=0;       for(int i=0;i<n;i++)       {           ans=max(ans,dp[i]);       }       return ans;   }
0
ayuak2000
This comment was deleted.
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.