Largest Divisible Subset LeetCode solution in Java
1class Solution {2public List<Integer> largestDivisibleSubset(int[] nums) {3Arrays.sort(nums);4int N = nums.length;5List<Integer> ans = new ArrayList<Integer>();6int[] dp = new int[N];7Arrays.fill(dp, 1);8int[] hash = new int[N];9for (int i = 0; i < N; i++) {10hash[i] = i;11}12int lastindex = 0;13int maxi = 1;14for (int i = 0; i < N; i++) {15for (int j = 0; j < i; j++) {16if (nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]) {17dp[i] = dp[j] + 1;18hash[i] = j;19}20if (dp[i] > maxi) {21maxi = dp[i];22lastindex = i;23}24}25} // for ends26ans.add(nums[lastindex]);27while (hash[lastindex] != lastindex) {28lastindex = hash[lastindex];29ans.add(nums[lastindex]);30}31return ans;32}33}