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:

nums: [1,2,3]

Result: [1,2] (of course, [1,3] will also be ok) Example 2:

nums: [1,2,4,8]

Result: [1,2,4,8]

Solution

public class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        if(nums == null || nums.length == 0) return new ArrayList<Integer>();
        Arrays.sort(nums);
        int dp[] = new int[nums.length];
        int prev[] = new int[nums.length];
        Arrays.fill(prev, -1);

        int max = 0;
        int idx = 0;
        for(int i = 0; i < nums.length; i++) {
            for(int j = 0; j < i; j++) {
                if(nums[i] % nums[j] == 0) {
                    if(dp[j]+1 > dp[i]) {
                        dp[i] = dp[j]+1;
                        prev[i] = j;
                    }
                }
            }
            if(dp[i] > max) {
                max = dp[i];
                idx = i;
            }
        }

        List<Integer> ans = new ArrayList<Integer>();
        while(idx != -1) {
            ans.add(nums[idx]);
            idx = prev[idx];
        }
        return ans;
    }
}

results matching ""

    No results matching ""