2017-10-06 06:41:19 +00:00
|
|
|
#############################
|
|
|
|
# Author: Aravind Kashyap
|
|
|
|
# File: lis.py
|
2020-05-22 06:10:11 +00:00
|
|
|
# comments: This programme outputs the Longest Strictly Increasing Subsequence in
|
|
|
|
# O(NLogN) Where N is the Number of elements in the list
|
2017-10-06 06:41:19 +00:00
|
|
|
#############################
|
2020-09-23 11:30:13 +00:00
|
|
|
from __future__ import annotations
|
2019-10-30 17:06:07 +00:00
|
|
|
|
2019-11-14 18:59:43 +00:00
|
|
|
|
2024-04-19 19:30:22 +00:00
|
|
|
def ceil_index(v, left, right, key):
|
|
|
|
while right - left > 1:
|
|
|
|
middle = (left + right) // 2
|
|
|
|
if v[middle] >= key:
|
|
|
|
right = middle
|
2019-10-05 05:14:13 +00:00
|
|
|
else:
|
2024-04-19 19:30:22 +00:00
|
|
|
left = middle
|
|
|
|
return right
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2017-10-06 06:41:19 +00:00
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
def longest_increasing_subsequence_length(v: list[int]) -> int:
|
2019-10-30 17:06:07 +00:00
|
|
|
"""
|
2022-10-12 22:54:20 +00:00
|
|
|
>>> longest_increasing_subsequence_length([2, 5, 3, 7, 11, 8, 10, 13, 6])
|
2019-10-30 17:06:07 +00:00
|
|
|
6
|
2022-10-12 22:54:20 +00:00
|
|
|
>>> longest_increasing_subsequence_length([])
|
2019-10-30 17:06:07 +00:00
|
|
|
0
|
2022-10-12 22:54:20 +00:00
|
|
|
>>> longest_increasing_subsequence_length([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13,
|
|
|
|
... 3, 11, 7, 15])
|
2019-10-30 17:06:07 +00:00
|
|
|
6
|
2022-10-12 22:54:20 +00:00
|
|
|
>>> longest_increasing_subsequence_length([5, 4, 3, 2, 1])
|
2019-10-30 17:06:07 +00:00
|
|
|
1
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
if len(v) == 0:
|
|
|
|
return 0
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
tail = [0] * len(v)
|
|
|
|
length = 1
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
tail[0] = v[0]
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
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:
|
2022-10-12 22:54:20 +00:00
|
|
|
tail[ceil_index(tail, -1, length - 1, v[i])] = v[i]
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
return length
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2017-10-06 06:41:19 +00:00
|
|
|
|
2019-07-10 04:59:39 +00:00
|
|
|
if __name__ == "__main__":
|
2019-10-30 17:06:07 +00:00
|
|
|
import doctest
|
2019-11-14 18:59:43 +00:00
|
|
|
|
2019-10-30 17:06:07 +00:00
|
|
|
doctest.testmod()
|