Program to find length of longest circular increasing subsequence in python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums, we have to find the length of the longest increasing subsequence and we are assuming the subsequence can wrap around to the beginning of the list.

So, if the input is like nums = [6, 5, 8, 2, 3, 4], then the output will be 5, as the longest increasing subsequence is [2, 3, 4, 6, 8].

To solve this, we will follow these steps −

  • a := make a list of size twice of nums and fill nums twice
  • ans := 0
  • for i in range 0 to size of nums, do
    • dp := a new list
    • for j in range i to size of nums + i - 1, do
      • n := a[j]
      • k := left most index to insert n into dp
      • if k is same as size of dp , then
        • insert n at the end of dp
      • otherwise,
        • dp[k] := n
      • ans := maximum of ans and size of dp
  • return ans

Let us see the following implementation to get better understanding −

Example 

Live Demo

import bisect
class Solution:
   def solve(self, nums):
      a = nums + nums
      ans = 0
      for i in range(len(nums)):
         dp = []
         for j in range(i, len(nums) + i):
            n = a[j]
            k = bisect.bisect_left(dp, n)
            if k == len(dp):
               dp.append(n)
            else:
               dp[k] = n
         ans = max(ans, len(dp))
      return ans

ob = Solution()
nums = [4, 5, 8, 2, 3, 4]
print(ob.solve(nums))

Input

[4, 5, 8, 2, 3, 4]

Output

5
raja
Published on 03-Dec-2020 10:14:26
Advertisements