Post

368 Largest Divisible Subset

368 Largest Divisible Subset

Largest Divisible Subset image

Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:

1
2
answer[i] % answer[j] == 0, or
answer[j] % answer[i] == 0

If there are multiple solutions, return any of them.

 

Example 1:

1
2
3
4
5
**Input:** nums = [1,2,3]
**Output:** [1,2]
**Explanation:** [1,3] is also accepted.

Example 2:

1
2
3
4
**Input:** nums = [1,2,4,8]
**Output:** [1,2,4,8]

 

Constraints:

1
2
3
1 <= nums.length <= 1000
1 <= nums[i] <= 2 * 109
All the integers in nums are **unique**.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

class Solution:
    def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
        nums.sort()
        if len(nums) == 1:
            return nums
        
        res = [(0,0)] * len(nums)
        mx = 0
        for i, k in enumerate(nums):
            t = 0
            p = 0
            for j in range(0,i+1):
                if k % nums[j] == 0:
                    if j != i and res[j][0] + 1 > t:
                        p = max(p, j)
                    t = max(res[j][0] + 1, t) 
                    mx = max(t,mx)
                    
            res[i] = (t,p)
        print(res, mx)
        if mx == 1:
            return [nums[0]]
        ans = [0] * mx
        index = 0
        for i, k in enumerate(res):
            if k[0] == mx:
                # found max
                index = k[1]
                ans[-1] = nums[i]

                break
        print(index)
        def rec(ans, index, i):
            if i == 0:
                ans[i] = nums[index]
                return
            ans[i] = nums[index]
            rec(ans, res[index][1], i - 1)
        rec(ans, index, len(ans)-2)
        return ans

        


        return res
        # T[n] = max(T[n-i]) for all i if k[i] % k[n-i] == 0
        # 

        



This post is licensed under CC BY 4.0 by the author.