Largest Divisible Subset
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)
Example 2:
Input: [1,2,4,8]
Output: [1,2,4,8]
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
// Sorting helps us reduce condition to only 1
// i.e -> nums[i]%nums[j]==0, where i>j
Arrays.sort(nums);
List<Integer>[] dp = new ArrayList[nums.length];
for (int i = 0; i < nums.length; i++)
dp[i] = new ArrayList<>();
int max = 0;
List<Integer> ans = new ArrayList<>();
// O(N*2N) => O(N^2)
for (int i = 0; i < nums.length; i++) {
// O(N)
for (int j = 0; j < i; j++)
if (nums[i] % nums[j] == 0 && dp[j].size() + 1 > dp[i].size())
// Copying by reference O(1)
dp[i] = dp[j];
// Copying by value O(N)
// Instead of copying every loop, we can just copy once in the end
// This will help us reduce time complexity from O(N^3) to O(N^2)
List<Integer> temp = new ArrayList<>();
for (int x : dp[i])
temp.add(x);
temp.add(nums[i]);
dp[i] = temp;
if (dp[i].size() > max) {
max = dp[i].size();
ans = dp[i];
}
}
return ans;
}
// O(n) space Solution
public List<Integer> largestDivisibleSubset(int[] nums) {
int n = nums.length;
int[] count = new int[n];
int[] pre = new int[n];
Arrays.sort(nums);
int max = 0, index = -1;
for (int i = 0; i < n; i++) {
count[i] = 1;
pre[i] = -1;
for (int j = i - 1; j >= 0; j--) {
if (nums[i] % nums[j] == 0) {
if (1 + count[j] > count[i]) {
count[i] = count[j] + 1;
pre[i] = j;
}
}
}
if (count[i] > max) {
max = count[i];
index = i;
}
}
List<Integer> res = new ArrayList<>();
while (index != -1) {
res.add(nums[index]);
index = pre[index];
}
return res;
}
}
Last updated