SDE & MLE Prep

368. Largest Divisible Subset

Problem

nums holds distinct positive integers. Return the largest subset in which, for every pair, one divides the other (any largest subset is accepted).

Example: [1,2,3] → [1,2] (or [1,3]); [1,2,4,8] → [1,2,4,8]

Constraints: n ≤ 1000.

Sort. If a | b and b | c then a | c, so it's LIS with "divides" instead of "<". Keep parent pointers to rebuild the subset.

Complexity: O(n²).

class Solution:
    def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
        nums.sort()
        n = len(nums)
        size, parent = [1] * n, [-1] * n
        for i in range(n):
            for j in range(i):
                if nums[i] % nums[j] == 0 and size[j] + 1 > size[i]:
                    size[i], parent[i] = size[j] + 1, j
        i = max(range(n), key=size.__getitem__)
        res = []
        while i != -1:
            res.append(nums[i])
            i = parent[i]
        return res[::-1]