Find the longest subsequence of an array having LCM at most K | Function to find the longest subsequence having LCM less than or equal to K ; Map to store unique elements and their frequencies ; Update the frequencies ; Array to store the count of numbers whom 1 <= X <= K is a multiple of ; Check every unique element ; Find all its multiples <= K ; Store its frequency ; Obtain the number having maximum count ; Condition to check if answer doesn 't exist ; Print the answer ; Driver code
< ? php function findSubsequence ( $ arr , $ n , $ k ) { $ M = array ( ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ M [ $ arr [ $ i ] ] = 0 ; for ( $ i = 0 ; $ i < $ n ; ++ $ i ) ++ $ M [ $ arr [ $ i ] ] ; $ numCount = array ( ) ; for ( $ i = 0 ; $ i <= $ k ; ++ $ i ) $ numCount [ $ i ] = 0 ; foreach ( $ M as $ key = > $ value ) { if ( $ key <= $ k ) { for ( $ i = 1 ; ; ++ $ i ) { if ( $ key * $ i > $ k ) break ; $ numCount [ $ key * $ i ] += $ value ; } } else break ; } $ lcm = 0 ; $ length = 0 ; for ( $ i = 1 ; $ i <= $ k ; ++ $ i ) { if ( $ numCount [ $ i ] > $ length ) { $ length = $ numCount [ $ i ] ; $ lcm = $ i ; } } if ( $ lcm == 0 ) echo - 1 << " STRNEWLINE " ; else { echo " LCM = " , ▁ $ lcm , STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " , Length = " , ▁ $ length , ▁ " " ; STRNEWLINE TABSYMBOL TABSYMBOL echo ▁ " Indexes = " for ( $ i = 0 ; $ i < $ n ; ++ $ i ) if ( $ lcm % $ arr [ $ i ] == 0 ) echo $ i , " ▁ " ; } } $ k = 14 ; $ arr = array ( 2 , 3 , 4 , 5 ) ; $ n = count ( $ arr ) ; findSubsequence ( $ arr , $ n , $ k ) ; ? >