Standard DP solution with an early termination


  • 0
    public class Solution {
        public List<Integer> largestDivisibleSubset(int[] nums) {
            List<Integer> res = new ArrayList<>();
            if (nums == null || nums.length == 0) return res;
            int[] dp = new int[nums.length];
            Arrays.sort(nums);
            int max = 0;
            for (int i = 1; i < nums.length; i++) {
                for (int j = i - 1; j >= 0; j--) {
                    if (nums[i] % nums[j] == 0) {
                        dp[i] = Math.max(dp[i], dp[j] + 1);
                        max = Math.max(max, dp[i]);
                        if (dp[j] == j + 1) break; // early termination
                    }
                }
            }
            for (int i = nums.length - 1; i >= 0; i--) {
                if (dp[i] == max) {
                    res.add(0, nums[i]);
                    max--;
                }
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.