Skip to content

Instantly share code, notes, and snippets.

@NodoFox
Created January 20, 2017 07:43
Show Gist options
  • Save NodoFox/0ff438903c9046a52b247426af30775e to your computer and use it in GitHub Desktop.
Save NodoFox/0ff438903c9046a52b247426af30775e to your computer and use it in GitHub Desktop.
public List<Integer> largestDivisibleSubset(int[] nums) {
Arrays.sort(nums);
int maxSubsetLength = 0;
int maxSubsetLengthStartIndex = 0;
int[] dp = new int[nums.length];
int[] parent = new int[nums.length]; // to keep track of the subset forming a chain
// Useful concept for other problems as well.
for(int i = nums.length - 1 ; i >= 0; i--) {
parent[i] = i;
for(int j = i; j < nums.length; j++) {
if(nums[j] % nums[i] == 0 && dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
parent[i] = j;
if(dp[i] > maxSubsetLength) {
maxSubsetLength = dp[i];
maxSubsetLengthStartIndex = i;
}
}
}
}
List<Integer> result = new ArrayList<>();
while(maxSubsetLengthStartIndex < nums.length) {
result.add(nums[maxSubsetLengthStartIndex]);
if(maxSubsetLengthStartIndex == parent[maxSubsetLengthStartIndex]) break;
maxSubsetLengthStartIndex = parent[maxSubsetLengthStartIndex];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment