Largest Divisible Subset Problem
Description
LeetCode Problem 368.
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:
- answer[i] % answer[j] == 0, or
- answer[j] % answer[i] == 0
If there are multiple solutions, return any of them.
Example 1:
Input: nums = [1,2,3]
Output: [1,2]
Explanation: [1,3] is also accepted.
Example 2:
Input: nums = [1,2,4,8]
Output: [1,2,4,8]
Constraints:
- 1 <= nums.length <= 1000
- 1 <= nums[i] <= 2 * 10^9
- All the integers in nums are unique.
Solution
Approach: Sort + Longest Divisible Chain (DP)
Divisibility is transitive: if a | b and b | c, then a | c. So after sorting, a set is valid exactly when each element divides the next one. The task becomes finding the longest chain a₁ | a₂ | … | aₖ in the sorted array, which is a longest-increasing-subsequence style DP.
- Sort
numsin increasing order. - Let
size[i]be the size of the largest valid subset whose largest element isnums[i]. It starts at 1 (justnums[i]). - For each
j < iwithnums[i] % nums[j] == 0,nums[i]can extend the best subset ending atnums[j], sosize[i] = max(size[i], size[j] + 1). Record thatjinprev[i]. - The answer ends at the index
bestwith the largestsize. Followprevfrom there back to-1to collect the elements.
Why is checking only nums[i] % nums[j] enough? Every element of the subset ending at nums[j] divides nums[j], so it also divides nums[i].
Example: nums = [1, 2, 3] gives size = [1, 2, 2]. Index 1 (value 2) is the first with size 2, and prev leads back to 1, giving [2, 1]. Any order of the elements is accepted.
Complexity: O(n2) time, where n is the length of nums: every pair (j, i) is checked once. O(n) space for size and prev.
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
nums.sort() # then every element only needs to be divisible by the earlier ones
n = len(nums)
size = [1] * n # size[i]: largest divisible subset whose largest element is nums[i]
prev = [-1] * n # index of the element before nums[i] in that subset, or -1
best = 0 # index where the largest subset ends
for i in range(n):
for j in range(i):
if nums[i] % nums[j] == 0 and size[j] + 1 > size[i]:
size[i] = size[j] + 1
prev[i] = j
if size[i] > size[best]:
best = i
# Follow prev from the end of the largest subset to rebuild it.
subset = []
i = best
while i != -1:
subset.append(nums[i])
i = prev[i]
return subset
Now write it from memory
Close the write-up and solve it yourself against the tests.