-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathfind-the-maximum-length-of-a-good-subsequence-i.py
66 lines (57 loc) · 1.69 KB
/
find-the-maximum-length-of-a-good-subsequence-i.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Time: O(n * k)
# Space: O(n * k)
import collections
# dp
class Solution(object):
def maximumLength(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
lookup = {x:i for i, x in enumerate(set(nums))}
dp = [[0]*len(lookup) for _ in xrange(k+1)]
result = [0]*(k+1)
for x in nums:
x = lookup[x]
for i in reversed(xrange(k+1)):
dp[i][x] = max(dp[i][x], result[i-1] if i-1 >= 0 else 0)+1
result[i] = max(result[i], dp[i][x])
return result[k]
# Time: O(n * k)
# Space: O(n * k)
import collections
# dp
class Solution2(object):
def maximumLength(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
dp = [collections.defaultdict(int) for _ in xrange(k+1)]
result = [0]*(k+1)
for x in nums:
for i in reversed(xrange(k+1)):
dp[i][x] = max(dp[i][x], result[i-1] if i-1 >= 0 else 0)+1
result[i] = max(result[i], dp[i][x])
return result[k]
# Time: O(n^2 * k)
# Space: O(n * k)
# dp
class Solution(object):
def maximumLength(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
dp = [[0]*(k+1) for _ in xrange(len(nums))]
result = 0
for i in xrange(len(nums)):
dp[i][0] = 1
for l in xrange(k+1):
for j in xrange(i):
dp[i][l] = max(dp[i][l], dp[j][l]+1 if nums[j] == nums[i] else 1, dp[j][l-1]+1 if l-1 >= 0 else 1)
result = max(result, dp[i][l])
return result