1
1
from __future__ import annotations
2
2
3
3
4
- def largest_divisible_subset (array ) :
4
+ def largest_divisible_subset (array : list [ int ]) -> list [ int ] :
5
5
"""
6
- Algorithm to find the biggest subset
7
- in the given array such that for any
6
+ Algorithm to find the biggest subset
7
+ in the given array such that for any
8
8
2 elements x and y in the subset,
9
9
either x divides y or y divides x
10
10
>>> largest_divisible_subset([1,16,7,8,4])
@@ -14,48 +14,49 @@ def largest_divisible_subset(array):
14
14
>>> largest_divisible_subset([1, 2, 4, 8])
15
15
[8, 4, 2, 1]
16
16
"""
17
- n = len (array )
17
+ array_size = len (array )
18
18
19
19
# Sort the array in ascending order
20
- # as the sequence does not matter
20
+ # as the sequence does not matter
21
21
# we only have to pick up a subset
22
22
array .sort ()
23
23
24
- # Initialize dp and hash arrays with 1s
25
- dp = [1 ] * n
26
- hash_arr = list (range (n ))
24
+ # Initialize memo and hash arrays with 1s
25
+ memo = [1 ] * array_size
26
+ hash_array = list (range (array_size ))
27
27
28
28
# Iterate through the array
29
- for i in range (n ):
29
+ for i in range (array_size ):
30
30
for prev_index in range (i ):
31
- if array [i ] % array [prev_index ] == 0 and 1 + dp [prev_index ] > dp [i ]:
32
- dp [i ] = 1 + dp [prev_index ]
33
- hash_arr [i ] = prev_index
31
+ if array [i ] % array [prev_index ] == 0 and 1 + memo [prev_index ] > memo [i ]:
32
+ memo [i ] = 1 + memo [prev_index ]
33
+ hash_array [i ] = prev_index
34
34
35
35
ans = - 1
36
36
last_index = - 1
37
37
38
38
# Find the maximum length and its corresponding index
39
- for i in range (n ):
40
- if dp [i ] > ans :
41
- ans = dp [i ]
39
+ for i in range (array_size ):
40
+ if memo [i ] > ans :
41
+ ans = memo [i ]
42
42
last_index = i
43
43
44
44
# Reconstruct the divisible subset
45
45
result = [array [last_index ]]
46
- while hash_arr [last_index ] != last_index :
47
- last_index = hash_arr [last_index ]
46
+ while hash_array [last_index ] != last_index :
47
+ last_index = hash_array [last_index ]
48
48
result .append (array [last_index ])
49
49
50
50
return result
51
51
52
+
52
53
if __name__ == "__main__" :
53
54
from doctest import testmod
54
55
55
56
testmod ()
56
57
57
58
array = [1 , 16 , 7 , 8 , 4 ]
58
59
59
- ans = largest_divisible_subset (array )
60
+ answer = largest_divisible_subset (array )
60
61
61
- print ("The longest divisible subset elements are:" , ans )
62
+ print ("The longest divisible subset elements are:" , answer )
0 commit comments