Skip to content

Commit e96dfb5

Browse files
committed
minor tweaks
1 parent 3fec355 commit e96dfb5

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed
Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
from __future__ import annotations
22

33

4-
def largest_divisible_subset(array):
4+
def largest_divisible_subset(array: list[int]) -> list[int]:
55
"""
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
88
2 elements x and y in the subset,
99
either x divides y or y divides x
1010
>>> largest_divisible_subset([1,16,7,8,4])
@@ -14,48 +14,49 @@ def largest_divisible_subset(array):
1414
>>> largest_divisible_subset([1, 2, 4, 8])
1515
[8, 4, 2, 1]
1616
"""
17-
n = len(array)
17+
array_size = len(array)
1818

1919
# Sort the array in ascending order
20-
# as the sequence does not matter
20+
# as the sequence does not matter
2121
# we only have to pick up a subset
2222
array.sort()
2323

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))
2727

2828
# Iterate through the array
29-
for i in range(n):
29+
for i in range(array_size):
3030
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
3434

3535
ans = -1
3636
last_index = -1
3737

3838
# 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]
4242
last_index = i
4343

4444
# Reconstruct the divisible subset
4545
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]
4848
result.append(array[last_index])
4949

5050
return result
5151

52+
5253
if __name__ == "__main__":
5354
from doctest import testmod
5455

5556
testmod()
5657

5758
array = [1, 16, 7, 8, 4]
5859

59-
ans = largest_divisible_subset(array)
60+
answer = largest_divisible_subset(array)
6061

61-
print("The longest divisible subset elements are:", ans)
62+
print("The longest divisible subset elements are:", answer)

0 commit comments

Comments
 (0)