Find the Largest divisor Subset in the Array | C ++ implementation of the approach ; Function to find the required subsequence ; Sort the array ; Keep a count of the length of the subsequence and the previous element ; Set the initial values ; Maximum length of the subsequence and the last element ; Run a loop for every element ; Check for all the divisors ; If the element is a divisor and the length of subsequence will increase by adding j as previous element of i ; Increase the count ; Update the max count ; Get the last index of the subsequence ; Print the element ; Move the index to the previous element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubSeq ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int count [ n ] = { 1 } ; int prev [ n ] = { -1 } ; memset ( count , 1 , sizeof ( count ) ) ; memset ( prev , -1 , sizeof ( prev ) ) ; int max = 0 ; int maxprev = -1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( arr [ i ] % arr [ j ] == 0 && count [ j ] + 1 > count [ i ] ) { count [ i ] = count [ j ] + 1 ; prev [ i ] = j ; } } if ( max < count [ i ] ) { max = count [ i ] ; maxprev = i ; } } int i = maxprev ; while ( i >= 0 ) { if ( arr [ i ] != -1 ) cout << arr [ i ] << " ▁ " ; i = prev [ i ] ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( int ) ; findSubSeq ( arr , n ) ; return 0 ; }