jayati

Longest Increasing Subsequence

Oct 28th, 2023
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6.  
  7.  
  8. class Solution
  9. {
  10.     public:
  11.     //Function to find length of longest increasing subsequence.
  12.     int longestSubsequence(int n, int a[])
  13.     {
  14.        vector<int>temp;
  15.         temp.push_back(a[0]);
  16.         for(int i=1;i<n;i++){
  17.             if(a[i]>temp.back())
  18.              temp.push_back(a[i]);
  19.             else{
  20.                 int idx = lower_bound(temp.begin(),temp.end(),a[i])-temp.begin();
  21.  
  22.                 temp[idx]=a[i];
  23.             }
  24.         }
  25.     return temp.size();
  26.        
  27.     }
  28. };
  29.  
  30. //{ Driver Code Starts.
  31. int main()
  32. {
  33.     //taking total testcases
  34.     int t,n;
  35.     cin>>t;
  36.     while(t--)
  37.     {
  38.         //taking size of array
  39.         cin>>n;
  40.         int a[n];
  41.        
  42.         //inserting elements to the array
  43.         for(int i=0;i<n;i++)
  44.             cin>>a[i];
  45.         Solution ob;
  46.         //calling method longestSubsequence()
  47.         cout << ob.longestSubsequence(n, a) << endl;
  48.     }
  49. }
  50.  
  51. // } Driver Code Ends
Add Comment
Please, Sign In to add comment