Largest divisible pairs subset | Function to find the longest Subsequence ; dp [ i ] is going to store size of largest divisible subset beginning with a [ i ] . ; Since last element is largest , d [ n - 1 ] is 1 ; Fill values for smaller elements . ; Find all multiples of a [ i ] and consider the multiple that has largest subset beginning with it . ; Return maximum value from dp [ ] ; Driver code
function largestSubset ( a , n ) { let dp = [ ] ; dp [ n - 1 ] = 1 ; for ( let i = n - 2 ; i >= 0 ; i -- ) { let mxm = 0 ; for ( let j = i + 1 ; j < n ; j ++ ) { if ( a [ j ] % a [ i ] == 0 a [ i ] % a [ j ] == 0 ) { mxm = Math . max ( mxm , dp [ j ] ) ; } } dp [ i ] = 1 + mxm ; } return Math . max ( ... dp ) ; } let a = [ 1 , 3 , 6 , 13 , 17 , 18 ] ; let n = a . length ; document . write ( largestSubset ( a , n ) ) ;