-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0300-longest-increasing-subsequence.py
More file actions
51 lines (42 loc) · 1.25 KB
/
0300-longest-increasing-subsequence.py
File metadata and controls
51 lines (42 loc) · 1.25 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# time complexity: O(nlogn)
# space complexity: O(n)
from bisect import bisect_left
from typing import List
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
sub = []
for num in nums:
i = bisect_left(sub, num)
if i == len(sub):
sub.append(num)
else:
sub[i] = num
return len(sub)
# time complexity: O(n^2)
# space complexity: O(n)
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
dp = [1] * len(nums)
for right in range(1, len(nums)):
for left in range(right):
if nums[right] > nums[left]:
dp[right] = max(dp[right], dp[left] + 1)
return max(dp)
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
sub = [nums[0]]
for num in nums[1:]:
if num > sub[-1]:
sub.append(num)
else:
i = 0
while num > sub[i]:
i += 1
sub[i] = num
return len(sub)
nums = [0, 1, 0, 3, 2, 3]
print(Solution().lengthOfLIS(nums))
nums = [0, 1, 0, 3, 2, 3]
print(Solution().lengthOfLIS(nums))
nums = [7, 7, 7, 7, 7, 7, 7]
print(Solution().lengthOfLIS(nums))