Longest Increasing Subsequence in Python


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

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def lengthOfLIS(self, nums):
      """
      :type nums: List[int]
      :rtype: int
      """
      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

Input

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

Output

4
raja
Published on 05-Feb-2020 10:37:34
Advertisements