forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request TheAlgorithms#147 from aravindiiitb/master
Added Code in Dynamic Programming section for Longest Strictly Increasing Subsequence in O(nlogn) time
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
dynamic_programming/longest_increasing_subsequence_O(nlogn).py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
############################# | ||
# Author: Aravind Kashyap | ||
# File: lis.py | ||
# comments: This programme outputs the Longest Strictly Increasing Subsequence in O(NLogN) | ||
# Where N is the Number of elements in the list | ||
############################# | ||
def CeilIndex(v,l,r,key): | ||
while r-l > 1: | ||
m = (l + r)/2 | ||
if v[m] >= key: | ||
r = m | ||
else: | ||
l = m | ||
|
||
return r | ||
|
||
|
||
def LongestIncreasingSubsequenceLength(v): | ||
if(len(v) == 0): | ||
return 0 | ||
|
||
tail = [0]*len(v) | ||
length = 1 | ||
|
||
tail[0] = v[0] | ||
|
||
for i in range(1,len(v)): | ||
if v[i] < tail[0]: | ||
tail[0] = v[i] | ||
elif v[i] > tail[length-1]: | ||
tail[length] = v[i] | ||
length += 1 | ||
else: | ||
tail[CeilIndex(tail,-1,length-1,v[i])] = v[i] | ||
|
||
return length | ||
|
||
|
||
v = [2, 5, 3, 7, 11, 8, 10, 13, 6] | ||
print LongestIncreasingSubsequenceLength(v) |