Iam_Sandeep

Longest Increasing Subsequence O(nlog n) O(n**2)

May 2nd, 2022 (edited)
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. class Solution:
  2.     def lengthOfLIS(self, nums: List[int]) -> int:
  3.         n=len(nums)
  4.         lis=[1]*n
  5.         lis[-1]=1
  6.         for i in range(n-1,-1,-1):
  7.             for j in range(i+1,n):
  8.                 if nums[i]<nums[j]:
  9.                     lis[i]=max(lis[i],1+lis[j])
  10.                 '''
  11.                Dont write this else.
  12.                Because Once you update lis[i] it will affect the ones of lis[1...i] and give wrong solutions
  13.                else:
  14.                    lis[i]=max(lis[i],lis[j])
  15.                '''
  16.         return max(lis)
  17. from bisect import bisect_left as bs
  18. class Solution:
  19.    
  20.     #Function to find length of longest increasing subsequence.
  21.     def longestSubsequence(self,a,n):
  22.         ans=[]
  23.         for i in a:
  24.             if not ans or ans[-1]<i:ans.append(i)
  25.             t=bs(ans,i)
  26.             ans[t]=i
  27.         return len(ans)
  28.        
Add Comment
Please, Sign In to add comment