Sort ascending
Only compare a later, larger value with an earlier, smaller one. The useful test is larger % smaller == 0.
The question
Given a list of distinct positive integers, return the largest subset in which every pair divides evenly in one direction: for any two values, the larger is divisible by the smaller. The output can be in ascending order. If several largest subsets exist, return any one.
Bottom-up DP is natural here: solve the best chain ending at each number, then connect it to an earlier chain.
Only compare a later, larger value with an earlier, smaller one. The useful test is larger % smaller == 0.
dp[i] is the longest chain ending at nums[i]. Every value starts at length 1; a valid earlier chain may extend it.
parent[i] stores the prior index chosen for the best chain. Follow those links backward, then reverse the answer.
Why one divisibility check is enough: if 8 is divisible by 4 and 4 by 2, then 8 is also divisible by 2. Transitivity makes every pair in the chain compatible.
Interactive walkthrough
Compare candidates, update dp and parent, then trace the answer.
Ready to sort the input.
Length 0
For the current ending i, look at every earlier j. Extend its chain only if the numbers divide evenly and it improves the length.
A tie keeps the first chain found. That is fine because the problem accepts any maximum subset.
Each number is a valid subset by itself, so every dp[i] starts at 1. A parent of -1 says that number starts its chain.
The largest dp[i] identifies an endpoint. Following parents visits the chain from largest to smallest, so reverse it before returning.
Python reference
This is the same transition and reconstruction used by the walkthrough. The empty input returns an empty subset.
from typing import List
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
if not nums:
return []
nums = sorted(nums)
n = len(nums)
dp = [1] * n
parent = [-1] * n
best_len = 1
best_end = 0
for i in range(n):
for j in range(i):
if nums[i] % nums[j] == 0 and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
parent[i] = j
if dp[i] > best_len:
best_len = dp[i]
best_end = i
answer = []
current = best_end
while current != -1:
answer.append(nums[current])
current = parent[current]
answer.reverse()
return answer