Advertisement
imashutosh51

Longest Increasing Subsequence

Jul 23rd, 2022 (edited)
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. /*
  2. Assume you have an array ie. dp where dp[j]=maximum size of longest increasing subsequence ending at j.
  3. suppose you are at ith position so it can be added next to any subsequence which is ending at jth position
  4. and arr[j]<arr[i].so you already have the longest increasing subsequence ending at j as dp[j] so now one
  5. element you are increasing in that subsequence so arr[i] can be dp[j]+1.
  6. We need maximum longest subsequence so take dp[i]=max(dp[j]+1,dp[i]);
  7. Initially dp array will be having 1 because each element alone make 1 size subsequence.
  8. */
  9.  
  10. class Solution {
  11. public:
  12.     int lengthOfLIS(vector<int>& arr) {
  13.         vector <int> dp(arr.size(),1);  //dp[i] will tell that longest string possible ending at ith index at array so search
  14.         int _max=1;                     //from j=0 to j<i and if(arr[j]<arr[i]),means ith element can be added to the subsequence
  15.         for(int i=1;i<arr.size();i++){   //ended at jt position because dp[j] contains the length of maximum subsequence ending at
  16.             for(int j=0;j<i;j++){        // jth position so dp[i]=maximum of all dp[j]+1 where arr[j]<arr[i].
  17.                 if(arr[j]<arr[i]) dp[i]=max(dp[i],dp[j]+1);   //our result subsequence will definitely end at some point of array,
  18.             }                                                 //so maximum of whole dp array array will be our answer.
  19.             _max=max(_max,dp[i]);
  20.         }
  21.         return _max;
  22.     }
  23. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement