368. Largest Divisible Subset — LeetCode
1 min readJun 15, 2020
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]
Here is my solution:
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> result = new ArrayList<>();
Arrays.sort(nums);
int dp[] = new int[nums.length];
int index[] = new int[nums.length];
Arrays.fill(dp, 1);
Arrays.fill(index, -1);
int maxSize = 0, maxIndex = -1;
for(int i=0; i<nums.length;i++) {
for(int j=i-1; j>=0;j--) {
if(nums[i] %nums[j] == 0 && dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
index[i] = j;
}
}
if (maxSize<dp[i]) {
maxSize = dp[i];
maxIndex = i;
}
}
int i = maxIndex;
while(i>=0) {
result.add(nums[i]);
i=index[i];
}
return result;
}
}
You can view full explanation on my YouTube channel. Here is the link