-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathlongest-subsequence-with-decreasing-adjacent-difference.py
More file actions
45 lines (42 loc) · 1.22 KB
/
longest-subsequence-with-decreasing-adjacent-difference.py
File metadata and controls
45 lines (42 loc) · 1.22 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
# Time: O(r^2 + n * r), r = max(nums)
# Space: O(r^2)
# dp
class Solution(object):
def longestSubsequence(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 2
mx = max(nums)
dp = [[0]*mx for _ in xrange(mx)]
for x in nums:
x -= 1
for nx in xrange(len(dp[x])):
d = abs(nx-x)
dp[x][d] = max(dp[x][d], dp[nx][d]+1)
for d in reversed(xrange(len(dp[x])-1)):
dp[x][d] = max(dp[x][d], dp[x][d+1])
result = max(result, dp[x][0])
return result
# Time: O(r^2 + n * r), r = max(nums)
# Space: O(r^2)
# dp
class Solution2(object):
def longestSubsequence(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 2
mx = max(nums)
dp = [[0]*mx for _ in xrange(mx)]
for x in reversed(nums):
x -= 1
for nx in xrange(len(dp[x])):
d = abs(nx-x)
dp[x][d] = max(dp[x][d], dp[nx][d]+1)
for d in xrange(1, len(dp[x])):
dp[x][d] = max(dp[x][d], dp[x][d-1])
result = max(result, dp[x][-1])
return result