Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. public List<Integer> largestDivisibleSubset(int[] nums) {
  2. Arrays.sort(nums);
  3. int maxSubsetLength = 0;
  4. int maxSubsetLengthStartIndex = 0;
  5. int[] dp = new int[nums.length];
  6. int[] parent = new int[nums.length]; // to keep track of the subset forming a chain
  7. // Useful concept for other problems as well.
  8. for(int i = nums.length - 1 ; i >= 0; i--) {
  9. parent[i] = i;
  10. for(int j = i; j < nums.length; j++) {
  11. if(nums[j] % nums[i] == 0 && dp[i] < dp[j] + 1) {
  12. dp[i] = dp[j] + 1;
  13. parent[i] = j;
  14. if(dp[i] > maxSubsetLength) {
  15. maxSubsetLength = dp[i];
  16. maxSubsetLengthStartIndex = i;
  17. }
  18. }
  19. }
  20. }
  21. List<Integer> result = new ArrayList<>();
  22. while(maxSubsetLengthStartIndex < nums.length) {
  23. result.add(nums[maxSubsetLengthStartIndex]);
  24. if(maxSubsetLengthStartIndex == parent[maxSubsetLengthStartIndex]) break;
  25. maxSubsetLengthStartIndex = parent[maxSubsetLengthStartIndex];
  26. }
  27. return result;
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement