forked from rajnishmaurya73/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLIS
More file actions
39 lines (31 loc) · 755 Bytes
/
LIS
File metadata and controls
39 lines (31 loc) · 755 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Longest increasing subsequence
# snip{
from bisect import bisect_left
def longest_increasing_subsequence(x):
"""Longest increasing subsequence
:param x: sequence
:returns: longest strictly increasing subsequence y
:complexity: `O(|x|*log(|y|))`
"""
n = len(x)
p = [None] * n
h = [None]
b = [float('-inf')] # - infinity
for i in range(n):
if x[i] > b[-1]:
p[i] = h[-1]
h.append(i)
b.append(x[i])
else:
k = bisect_left(b, x[i])
h[k] = i
b[k] = x[i]
p[i] = h[k - 1]
# extraire solution
q = h[-1]
s = []
while q is not None:
s.append(x[q])
q = p[q]
return s[::-1]
# snip}