Largest Divisible Subset
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example
Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)
Solution
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
dp = [[]]
for n in sorted(nums):
dp.append([n]+max((s for s in dp if not s or n%s[0]==0),key=len))
return max(dp, key=len)