
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Length of Longest Circular Increasing Subsequence in Python
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
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
Advertisements