Largest Divisible Subset
Pattern: LIS family
Sort the numbers. Then a set where every pair divides is a chain where each divides the next, so it is LIS with 'a[j] divides a[i]' instead of 'a[j] < a[i]'. Store prev[i] to print it.
The problem
Given distinct positive integers, return a largest subset where every pair (x, y) has x % y == 0 or y % x == 0. Any largest subset is accepted: the tests check its size and that every pair divides.
Think first
- After sorting, what is enough to check?
- Why does it chain?
- Which DP does that look like?
Hints
Brute force, and why it fails
Try every subset and check every pair: 2ⁿ × n².
The key insight
Sorting turns 'every pair divides' into 'each divides the next', which is an LIS-style chain.
Dry run
[1, 2, 3], sorted. 2 % 1 == 0: len 2. 3 % 1 == 0: len 2; 3 % 2 != 0.
Step 1 of 2
The plan
sort
len[i] = 1 + max len[j] for j < i with a[i] % a[j] == 0; prev[i] = that j
follow prev from the best end
Complexity
- Time
O(n²)- Space
O(n)
Every pair once.
Edge cases
- One number.
- All primes: one number (or 1 with one prime).
- Powers of 2: all of them.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
int[] a = nums.clone();
Arrays.sort(a); // sorted, a chain where each divides the next is enough
int n = a.length;
int[] len = new int[n], prev = new int[n];
int end = 0;
for (int i = 0; i < n; i++) {
len[i] = 1;
prev[i] = -1;
for (int j = 0; j < i; j++)
if (a[i] % a[j] == 0 && len[j] + 1 > len[i]) { len[i] = len[j] + 1; prev[i] = j; } // like LIS, with "divides"
if (len[i] > len[end]) end = i;
}
List<Integer> out = new ArrayList<>();
for (int i = end; i != -1; i = prev[i]) out.add(a[i]);
return out;
}
}C++
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
vector<int> a(nums);
sort(a.begin(), a.end()); // sorted, a chain where each divides the next is enough
int n = static_cast<int>(a.size());
vector<int> len(n, 1), prev(n, -1);
int end = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++)
if (a[i] % a[j] == 0 && len[j] + 1 > len[i]) { len[i] = len[j] + 1; prev[i] = j; } // like LIS, with "divides"
if (len[i] > len[end]) end = i;
}
vector<int> out;
for (int i = end; i != -1; i = prev[i]) out.push_back(a[i]);
return out;
}
};Python
class Solution:
def largestDivisibleSubset(self, nums: list[int]) -> list[int]:
a = sorted(nums) # sorted, a chain where each divides the next is enough
n = len(a)
length, prev = [1] * n, [-1] * n
for i in range(n):
for j in range(i):
if a[i] % a[j] == 0 and length[j] + 1 > length[i]: # like LIS, with "divides"
length[i], prev[i] = length[j] + 1, j
i, out = max(range(n), key=lambda k: length[k]), []
while i != -1:
out.append(a[i])
i = prev[i]
return outCommon mistakes
- Not sorting first.
- Checking only the last pair without sorting.