You're given a set of distinct positive integers, and your task is to find the largest subset where every pair of elements has a special divisibility property.
Specifically, for any two elements a and b in your chosen subset, either:
a % b == 0(a is divisible by b), ORb % a == 0(b is divisible by a)
This means that in a valid subset, you can always arrange the numbers in a sequence where each number divides the next one. For example, [1, 2, 4, 8] works because 1|2, 2|4, and 4|8.
Goal: Return the largest such subset. If multiple subsets have the same maximum size, return any one of them.
Example: Given [1, 2, 3, 4, 6], the answer could be [1, 2, 4] or [1, 2, 6] or [1, 3, 6] - all have length 3.
Input & Output
Visualization
Time & Space Complexity
O(n log n) for sorting + O(nยฒ) for DP transitions
Space for DP array, parent array, and result
Constraints
- 1 โค nums.length โค 1000
- 1 โค nums[i] โค 2 ร 109
- All integers in nums are distinct
- You may return the answer in any order