Largest Divisible Subset
Thoughts
Code
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
int n = nums.length, max = 0, maxIndex = 0;
int[] f = new int[n], pres = new int[n];
List<Integer> res = new ArrayList<>();
if (n == 0) {
return res;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
f[i] = 1;
pres[i] = i;
for (int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0 && f[j] + 1 > f[i]) {
pres[i] = j;
f[i] = f[j] + 1;
}
}
if (f[i] > max) {
max = f[i];
maxIndex = i;
}
}
while (pres[maxIndex] != maxIndex) {
res.add(nums[maxIndex]);
maxIndex = pres[maxIndex];
}
res.add(nums[maxIndex]);
return res;
}
}Analysis
Last updated