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