Skip to content

Commit

Permalink
feature: longest increasing subsequence bs revisit
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Jan 5, 2024
1 parent dd82fb8 commit d15f22f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
19 changes: 19 additions & 0 deletions dynamic_programming/LongestIncreasingSubsequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,25 @@ def length_of_lis_bottom_up(self, nums: List[int]) -> int:
return max(dp)


# O(n * log(n)) time || O(n) space
def length_of_lis_bs(self, nums: List[int]) -> int:
tails = [0] * len(nums)
res = 0
for num in nums:
low, high = 0, res
while low != high:
mid = low + (high - low) // 2
if tails[mid] < num:
low = mid + 1
else:
high = mid

tails[low] = num
res = max(res, low + 1)

return res


# O(n * log(n)) time || O(n) space
def length_of_lis(self, nums: List[int]) -> int:
sub = []
Expand Down
5 changes: 4 additions & 1 deletion dynamic_programming/test/test_length_of_lis.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import unittest

from dynamic_programming.LongestIncreasingSubsequence import length_of_lis, length_of_lis_bottom_up
from dynamic_programming.LongestIncreasingSubsequence import length_of_lis, length_of_lis_bottom_up, length_of_lis_bs


class MyTestCase(unittest.TestCase):
def test_length_of_lis(self):
self.assertEqual(4, length_of_lis_bottom_up(self, [10, 9, 2, 5, 3, 7, 101, 18]))
self.assertEqual(4, length_of_lis_bs(self, [10, 9, 2, 5, 3, 7, 101, 18]))
self.assertEqual(4, length_of_lis(self, [10, 9, 2, 5, 3, 7, 101, 18]))

def test_length_of_lis_1(self):
self.assertEqual(4, length_of_lis_bottom_up(self, [0, 1, 0, 3, 2, 3]))
self.assertEqual(4, length_of_lis_bs(self, [0, 1, 0, 3, 2, 3]))
self.assertEqual(4, length_of_lis(self, [0, 1, 0, 3, 2, 3]))

def test_length_of_lis_2(self):
self.assertEqual(1, length_of_lis_bottom_up(self, [7, 7, 7, 7, 7, 7, 7]))
self.assertEqual(1, length_of_lis_bs(self, [7, 7, 7, 7, 7, 7, 7]))
self.assertEqual(1, length_of_lis(self, [7, 7, 7, 7, 7, 7, 7]))


Expand Down

0 comments on commit d15f22f

Please sign in to comment.