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.
OR
Given a set of distinct positive integers, find the largest subset such that every pair of elements in the subset (i, j) satisfies either i % j = 0 or j % i = 0.
Method 1 - Use DP and Longest Increasing Subsequence#
We know that for two numbers a and b, a % b == 0 if a >= b. Now lets see how to convert the problem to Longest Increasing Subsequence (LIS).
Let’s consider the example [1, 2, 3, 6]:
Start with the smallest number: 2 % 1 == 0 is true, so we can form the subset {1, 2}.
Continue with the next number: 3 % 1 == 0 is true, so we can form another subset {1, 3}.
For the number 6, 6 % 2 == 0 gives us a subset {1, 2, 6} and 6 % 3 == 0 gives {1, 3, 6}.
While creating these subsets, note that 2 and 3 do not belong to the same subset. Our implementation handles this during the construction of the subsets.
Also, in example our list was sorted but if it is not sorted, we may have to do 2 mod operations => a%b == 0 and b%a == 0. So, when the array is sorted, than we can just to b%a==0 provided b comes after a. So, sorting the array is not prerequisite, but helps.
Method 2 - Using LIS but Combine Functions From Method 1#
We can combine all the functions in Method 1 using prev array, storing indices of previous value when creating LIS. We also tracking max index so that we can construct result later.
Sort the Array: Sorting helps reduce redundant checks. If not sorted, we may have to check both conditions: a % b == 0 and b % a == 0.
Dynamic Programming Setup: Use two arrays: dp to keep track of the size of the largest divisible subset ending at each index, and prev to help reconstruct the subset.
Update Subset Lengths: Iterate through the sorted array and update dp and prev based on the divisibility condition.
Reconstruct the Subset: Using the prev array, reconstruct the largest subset and return it.