-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmaximize-consecutive-elements-in-an-array-after-modification.py
75 lines (66 loc) · 1.9 KB
/
maximize-consecutive-elements-in-an-array-after-modification.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
67
68
69
70
71
72
73
74
75
# Time: O(nlogn)
# Space: O(1)
# sort, dp
class Solution(object):
def maxSelectedElements(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
result = 1
dp = [1]*2 # dp[i]: the maximum length of a consecutive sequence ending with x+i, where x is the last visited value
for i in xrange(1, len(nums)):
if nums[i] == nums[i-1]:
dp[1] = dp[0]+1
elif nums[i] == nums[i-1]+1:
dp[0] += 1
dp[1] += 1
elif nums[i] == nums[i-1]+2:
dp[0] = dp[1]+1
dp[1] = 1
else:
dp[0] = dp[1] = 1
result = max(result, dp[0], dp[1])
return result
# Time: O(nlogn)
# Space: O(n)
import collections
# sort, dp
class Solution2(object):
def maxSelectedElements(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
dp = collections.defaultdict(int)
dp[nums[0]] = dp[nums[0]+1] = 1
for i in xrange(1, len(nums)):
if nums[i] == nums[i-1]:
dp[nums[i]+1] = dp[nums[i]]+1
elif nums[i] == nums[i-1]+1:
dp[nums[i]+1] = dp[nums[i]]+1
dp[nums[i]] = dp[nums[i]-1]+1
elif nums[i] == nums[i-1]+2:
dp[nums[i]] = dp[nums[i]-1]+1
dp[nums[i]+1] = 1
else:
dp[nums[i]] = dp[nums[i]+1] = 1
return max(dp.itervalues())
# Time: O(nlogn)
# Space: O(n)
import collections
# sort, dp
class Solution3(object):
def maxSelectedElements(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
dp = collections.defaultdict(int)
for x in nums:
dp[x+1] = dp[x]+1
dp[x] = dp[x-1]+1
return max(dp.itervalues())