Longest Increasing Subsequence in Python

PythonServer Side ProgrammingProgramming

Suppose we have an unsorted list of integers. We have to find the longest increasing subsequence. So if the input is [10,9,2,5,3,7,101,18], then the output will be 4, as the increasing subsequence is [2,3,7,101]

To solve this, we will follow these steps −

  • trail := an array of length 0 to length of nums – 1, and fill this with 0
  • size := 0
  • for x in nums
    • i := 0, j := size
    • while i is not j
      • mid := i + (j - i) / 2
      • if trails[mid] < x, then i := mid + 1, otherwise j := mid
    • trails[i] := x
    • size := maximum of i + 1 and size
  • return size

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def lengthOfLIS(self, nums):
      tails =[0 for i in range(len(nums))]
      size = 0
      for x in nums:
         i=0
         j=size
         while i!=j:
            mid = i + (j-i)//2
            if tails[mid]< x:
               i= mid+1
            else:
               j = mid
               tails[i] = x
               size = max(i+1,size)
               #print(tails)
      return size
ob1 = Solution()
print(ob1.lengthOfLIS([10,9,2,5,3,7,101,18]))

Input

[10,9,2,5,3,7,101,18]

Output

4
raja
Published on 05-Feb-2020 15:07:34
Advertisements