- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Let us see the following implementation to get better understanding −
Example
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
- Related Articles
- Longest Increasing Subsequence
- Longest Continuous Increasing Subsequence in C++
- Program to find length of longest increasing subsequence in Python
- Java Program for Longest Increasing Subsequence
- Number of Longest Increasing Subsequence in C++
- Program to find length of longest circular increasing subsequence in python
- Increasing Triplet Subsequence in Python
- Program to find length of longest increasing subsequence with at least k odd values in Python
- C++ Program to Find the Longest Increasing Subsequence of a Given Sequence
- Longest Common Subsequence
- Longest Bitonic Subsequence
- Longest Palindromic Subsequence
- Longest Increasing Path in a Matrix in Python
- Longest Common Subsequence in C++
- Longest Harmonious Subsequence in C++

Advertisements