Largest Divisible Subset in C++


Suppose we have a set of distinct positive integers, we have to find the largest subset such that every pair like (Si, Sj) of elements in this subset satisfies: Si mod Sj = 0 or Sj mod Si = 0.

So if the input is like [1,2,3], the possible result may come like [1,2] or [1,3]

To solve this, we will follow these steps −

  • Create an array ret, set endpoint := 0, retLen := 1, n := size of nums

  • if n is 0, then return empty set

  • sort nums array

  • create two arrays len and par of size n, initialize len by 1, and par with 0

  • for i in range 1 to n – 1

    • par[i] := i

    • for j in range 0 to i – 1

      • if nums[i] mod nums[j] = 0 and len[j] + 1 > len[i], then

        • len[i] := len[j] + 1

        • par[i] := j

    • if len[j] > retLen, then retLen := len[i] and endpoint := i

  • insert nums[endPoint] into ret

  • while endpoint is not same as par[endPoint]

    • endpoint := par[endPoint]

    • insert nums[endPoint] into ret

  • reverse the list ret and return ret

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> largestDivisibleSubset(vector<int>& nums) {
      vector <int> ret;
      int endPoint = 0;
      int retLen = 1;
      int n = nums.size();
      if(!n) return {};
      sort(nums.begin(), nums.end());
      vector <int> len(n, 1);
      vector <int> par(n, 0);
      for(int i = 1; i < n; i++){
         par[i] = i;
         for(int j = 0; j < i; j++){
            if(nums[i] % nums[j] == 0 && len[j] + 1 > len[i]){
               len[i] = len[j] + 1;
               par[i] = j;
            }
         }
         if(len[i] > retLen){
            retLen = len[i];
            endPoint = i;
         }
      }
      ret.push_back(nums[endPoint]);
      while(endPoint != par[endPoint]){
         endPoint = par[endPoint];
         ret.push_back(nums[endPoint]);
      }
      reverse(ret.begin(), ret.end());
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3};
   print_vector(ob.largestDivisibleSubset(v));
}

Input

[1,2,3]

Output

[1, 2, ]

Updated on: 02-May-2020

53 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements