Skip to content

largest divisible subset #9825

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Oct 5, 2023
20 changes: 14 additions & 6 deletions dynamic_programming/largest_divisible_subset.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def largest_divisible_subset(array: list[int]) -> list[int]:
[-3]
>>> largest_divisible_subset([1, 2, 4, 8])
[8, 4, 2, 1]
>>> largest_divisible_subset((1, 2, 4, 8))
>>> largest_divisible_subset([1, 2, 4, 8])
[8, 4, 2, 1]
>>> largest_divisible_subset([1, 1, 1])
[1, 1, 1]
Expand All @@ -40,7 +40,9 @@ def largest_divisible_subset(array: list[int]) -> list[int]:
# Iterate through the array
for i, item in enumerate(array):
for prev_index in range(i):
if item % array[prev_index] == 0 and 1 + memo[prev_index] > memo[i]:
if ((array[prev_index] != 0 and item % array[prev_index]) == 0) and (
(1 + memo[prev_index]) > memo[i]
):
memo[i] = 1 + memo[prev_index]
hash_array[i] = prev_index

Expand All @@ -54,6 +56,8 @@ def largest_divisible_subset(array: list[int]) -> list[int]:
last_index = i

# Reconstruct the divisible subset
if last_index == -1:
return []
result = [array[last_index]]
while hash_array[last_index] != last_index:
last_index = hash_array[last_index]
Expand All @@ -71,7 +75,11 @@ def largest_divisible_subset(array: list[int]) -> list[int]:
print(
f"The longest divisible subset of {items} is {largest_divisible_subset(items)}."
)

answer = largest_divisible_subset(array)

print("The longest divisible subset elements are:", answer)
if len(items) == 0:
print("No items to form subset!")
else:
answer = largest_divisible_subset(items)
if len(answer) == 0:
print("No subset found")
else:
print("The longest divisible subset elements are:", answer)