Largest Divisible Subset - Medium - L

1 minute read

Published:

Question

  • https://leetcode.com/problems/largest-divisible-subset/

Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:

answer[i] % answer[j] == 0, or
answer[j] % answer[i] == 0

If there are multiple solutions, return any of them.

Approach

  • bucketing and dp

Solution

class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& arr) {
        vector<int> ans;
        int n = arr.size();
        sort(arr.begin(), arr.end());
  
        // To store count of divisors of all elements
        vector<int> divCount(n, 1);
  
        // To store previous divisor in result
        vector<int> prev(n, -1);
  
        // To store index of largest element in maximum
        // size subset
        int max_ind = 0;
  
        // In i'th iteration, we find length of chain
        // ending with arr[i]
        for (int i=1; i<n; i++)
        {
            // Consider every smaller element as previous
            // element.
            for (int j=0; j<i; j++)
            {
                if (arr[i]%arr[j] == 0)
                {
                    if (divCount[i] < divCount[j] + 1)
                    {
                        divCount[i] = divCount[j]+1;
                        prev[i] = j;
                    }
                }
            }
  
            // Update last index of largest subset if size
            // of current subset is more.
            if (divCount[max_ind] < divCount[i])
                max_ind = i;
        }
  
        // Print result
        int k = max_ind;
        while (k >= 0)
        {
            ans.push_back(arr[k]);
            k = prev[k];
        }
        return ans;
    }
};