368. Largest Divisible Subset

  • Difficulty: Medium

  • Topics: Math, Dynamic Programming

  • Similar Questions:

Problem:

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:

Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)

Example 2:

Input: [1,2,4,8]
Output: [1,2,4,8]
</div> </div>

Solutions:

class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        if (nums.size() == 0)   return {}; // this is essential; otherwiseret.push_back(nums[index]); is incorrect
        sort(nums.begin(), nums.end());
        int n = nums.size();
        vector<int> dp(n, 1);

        for (int i = 1; i < nums.size(); ++i) {
            for (int j = 0; j < i; ++j) {
                if (nums[i] % nums[j] == 0) {
                    dp[i] = max(dp[i], 1 + dp[j]);
                }
            }
        }

        int index = 0;
        int maxVal = 0;

        for (int i = 0; i < nums.size(); ++i) {
            if (dp[i] > maxVal) {
                index = i;
                maxVal = dp[i];
            }
        }

        vector<int> ret;
        ret.push_back(nums[index]);
        --index;
        while (index >= 0) {
            if (ret.back() % nums[index] == 0 && dp[index] +  ret.size() == maxVal) {
                ret.push_back(nums[index]);
            }

            --index;
        }

        return ret;

    }
};

results matching ""

    No results matching ""