- Related Questions & Answers
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest increasing subsequence with at least k odd values in Python
- Longest Increasing Subsequence in Python
- Longest Increasing Subsequence
- Program to find length of longest common subsequence in C++
- Program to find length of longest bitonic subsequence in C++
- Program to find length of longest common subsequence of three strings in Python
- Java Program for Longest Increasing Subsequence
- Program to find out the length of longest palindromic subsequence using Python
- Program to find length of longest strictly increasing then decreasing sublist in Python
- Program to find length of longest arithmetic subsequence of a given list in Python
- C++ Program to Find the Longest Increasing Subsequence of a Given Sequence

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

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

5

Advertisements