-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSet.py
More file actions
34 lines (31 loc) · 831 Bytes
/
Copy pathMaxSet.py
File metadata and controls
34 lines (31 loc) · 831 Bytes
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
def max_independent_set(nums):
n = len(nums)
if max(nums) < 0 or max(nums) == 0:
return []
cache = [0 for x in range(n + 1)]
take = [False for x in range(n + 1)]
for i in range(n + 1):
if i == 0:
cache[i] = 0
elif i == 1:
cache[i] = nums[0]
take[i] = True
else:
take_val = nums[i - 1] + cache[i - 2]
skip_val = cache[i - 1]
if take_val > skip_val:
cache[i] = take_val
take[i] = True
else:
cache[i] = skip_val
result = []
i = n
while i >= 1:
if take[i]:
result.append(nums[i - 1])
i -= 2
else:
i -= 1
return result[::-1]
# nums = [7,2,5,8,6]
# print(max_independent_set(nums))